首页 文章

如何使用PHP发送电子邮件?

提问于
浏览
256

我在网站上使用PHP,我想添加电子邮件功能 .

我安装了WAMPSERVER .

如何使用PHP发送电子邮件?

13 回答

  • 2

    另请查看PEAR邮件包Pear Mail Page

    它似乎比内置的标准mail()函数更强大(如果标准函数不足) .

    以下是此页面的摘录,显示了如何使用它 . PEAR Mail send() usage

    <?php
        include('Mail.php');
    
        $recipients = 'joe@example.com';
    
        $headers['From']    = 'richard@example.com';
        $headers['To']      = 'joe@example.com';
        $headers['Subject'] = 'Test message';
    
        $body = 'Test message';
    
        $smtpinfo["host"] = "smtp.server.com";
        $smtpinfo["port"] = "25";
        $smtpinfo["auth"] = true;
        $smtpinfo["username"] = "smtp_user";
        $smtpinfo["password"] = "smtp_password";
    
    
        // Create the mail object using the Mail::factory method
        $mail_object =& Mail::factory("smtp", $smtpinfo); 
    
        $mail_object->send($recipients, $headers, $body);
    ?>
    
  • 4

    Sent the Email with this script

    <h2>Test Mail</h2>
    <?php
    
    if (!isset($_POST["submit"]))
      {
      ?>
      <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
      From: <input type="text" name="from"><br>
      Subject: <input type="text" name="subject"><br>
      Message: <textarea rows="10" cols="40" name="message"></textarea><br>
      <input type="submit" name="submit" value="Click To send mail">
      </form>
      <?php
      }
    
    else
    
      {
    
      if (isset($_POST["from"]))
        {
        $from = $_POST["from"]; // sender
        $subject = $_POST["subject"];
        $message = $_POST["message"];
    
        $message = wordwrap($message, 70);
    
        mail("Test@example.com",$subject,$message,"From: $from\n");
        echo "Thank you for sending an email";
        }
      }
    ?>
    

    按“发送电子邮件”按钮后,电子邮件将发送到Test@example.com

  • 1

    您可以使用Postmark,Sendgrid等邮件Web服务 .

    Sendgrid vs Postmark vs Amazon SES and other email/SMTP API providers?

    编辑:我现在只使用Google Gmail API . 我无法向我的雇主's organization due to strict filters. But Gmail works as long as you don'垃圾邮件发送提醒电子邮件 .

  • 40

    对于大多数项目,我现在使用Swift mailer . 这是一种非常灵活和优雅的面向对象的发送电子邮件的方法,由给我们流行的Symfony frameworkTwig template engine的人创建 .


    基本用法:

    require 'mail/swift_required.php';
    
    $message = Swift_Message::newInstance()
        // The subject of your email
        ->setSubject('Jane Doe sends you a message')
        // The from address(es)
        ->setFrom(array('jane.doe@gmail.com' => 'Jane Doe'))
        // The to address(es)
        ->setTo(array('frank.stevens@gmail.com' => 'Frank Stevens'))
        // Here, you put the content of your email
        ->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');
    
    if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
        echo json_encode([
            "status" => "OK",
            "message" => 'Your message has been sent!'
        ], JSON_PRETTY_PRINT);
    } else {
        echo json_encode([
            "status" => "error",
            "message" => 'Oops! Something went wrong!'
        ], JSON_PRETTY_PRINT);
    }
    

    有关如何使用Swift邮件程序的更多信息,请参阅the official documentation .

  • 372

    从PHP发送电子邮件的核心方法是使用mail()函数,但有几个可以使用的SDK可以简化集成:

    附:我受雇于Pepipost .

  • 7

    如果您对html格式的电子邮件感兴趣,请确保在 Headers 中传递 Content-type: text/html; . 例:

    // multiple recipients
    $to  = 'aidan@example.com' . ', '; // note the comma
    $to .= 'wez@example.com';
    
    // subject
    $subject = 'Birthday Reminders for August';
    
    // message
    $message = '
    <html>
    <head>
      <title>Birthday Reminders for August</title>
    </head>
    <body>
      <p>Here are the birthdays upcoming in August!</p>
      <table>
        <tr>
          <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
        </tr>
        <tr>
          <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
        </tr>
        <tr>
          <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
        </tr>
      </table>
    </body>
    </html>
    ';
    
    // To send HTML mail, the Content-type header must be set
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    
    // Additional headers
    $headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
    $headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
    $headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
    $headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";
    
    // Mail it
    mail($to, $subject, $message, $headers);
    

    有关更多详细信息,请查看php mail函数 .

  • 12

    本机PHP函数 Mail() 对我不起作用 . 它发出消息:

    503此邮件服务器在尝试发送到非本地电子邮件地址时需要进行身份验证

    所以我通常使用 PHPMailer

    我已经在GitHub中下载了5.2.23版本 .

    我刚刚选择了2个文件并将它们放在我的源代码PHP根目录中

    class.phpmailer.php class.smtp.php

    在PHP文件中,需要添加它

    require_once('class.smtp.php');
    require_once('class.phpmailer.php');
    

    在此之后,它只是代码:

    require_once('class.smtp.php');
    require_once('class.phpmailer.php');
    ... 
    //----------------------------------------------
    // Send an e-mail. Returns true if successful 
    //
    //   $to - destination
    //   $nameto - destination name
    //   $subject - e-mail subject
    //   $message - HTML e-mail body
    //   altmess - text alternative for HTML.
    //----------------------------------------------
    function sendmail($to,$nameto,$subject,$message,$altmess)  {
    
      $from  = "yourcontact@yourdomain.com"
      $namefrom = "yourname";
      $mail = new PHPMailer();  
      $mail->CharSet = 'UTF-8';
      $mail->isSMTP();   // by SMTP
      $mail->SMTPAuth   = true;   // user and password
      $mail->Host       = "localhost";
      $mail->Port       = 25;
      $mail->Username   = $from;  
      $mail->Password   = "yourpassword";
      $mail->SMTPSecure = "";    // options: 'ssl', 'tls' , ''  
      $mail->setFrom($from,$namefrom);   // From (origin)
      $mail->addCC($from,$namefrom);      // There is also addBCC
      $mail->Subject  = $subject;
      $mail->AltBody  = $altmess;
      $mail->Body = $message;
      $mail->isHTML();   // Set HTML type
    //$mail->addAttachment("attachment");  
      $mail->addAddress($to, $nameto);
      return $mail->send();
    }
    

    它就像一个魅力

  • 15

    试试这个:

    <?php
    $to = "somebody@example.com";
    $subject = "My subject";
    $txt = "Hello world!";
    $headers = "From: webmaster@example.com" . "\r\n" .
    "CC: somebodyelse@example.com";
    
    mail($to,$subject,$txt,$headers);
    ?>
    
  • 103

    完整的代码示例..

    尝试一次..

    <?php
    // Multiple recipients
    $to = 'johny@example.com, sally@example.com'; // note the comma
    
    // Subject
    $subject = 'Birthday Reminders for August';
    
    // Message
    $message = '
    <html>
    <head>
      <title>Birthday Reminders for August</title>
    </head>
    <body>
      <p>Here are the birthdays upcoming in August!</p>
      <table>
        <tr>
          <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
        </tr>
        <tr>
          <td>Johny</td><td>10th</td><td>August</td><td>1970</td>
        </tr>
        <tr>
          <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
        </tr>
      </table>
    </body>
    </html>
    ';
    
    // To send HTML mail, the Content-type header must be set
    $headers[] = 'MIME-Version: 1.0';
    $headers[] = 'Content-type: text/html; charset=iso-8859-1';
    
    // Additional headers
    $headers[] = 'To: Mary <mary@example.com>, Kelly <kelly@example.com>';
    $headers[] = 'From: Birthday Reminder <birthday@example.com>';
    $headers[] = 'Cc: birthdayarchive@example.com';
    $headers[] = 'Bcc: birthdaycheck@example.com';
    
    // Mail it
    mail($to, $subject, $message, implode("\r\n", $headers));
    ?>
    
  • 7

    使用PHP的mail()函数是可能的 . 请记住,邮件功能在本地服务器中不起作用 .

    <?php
    $to      = 'nobody@example.com';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: webmaster@example.com' . "\r\n" .
        'Reply-To: webmaster@example.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    
    mail($to, $subject, $message, $headers);
    ?>
    

    参考:

  • 0
    <?php
    include "db_conn.php";//connection file
    require "PHPMailerAutoload.php";// it will be in PHPMailer
    require "class.smtp.php";// it will be in PHPMailer
    require "class.phpmailer.php";// it will be in PHPMailer
    
    
    $response = array();
    $params = json_decode(file_get_contents("php://input"));
    
    if(!empty($params->email_id)){
    
        $email_id = $params->email_id;
        $flag=false;
        echo "something";
        if(!filter_var($email_id, FILTER_VALIDATE_EMAIL))
        {
            $response['ERROR']='EMAIL address format error'; 
            echo json_encode($response,JSON_UNESCAPED_SLASHES);
            return;
        }
        $sql="SELECT * from sales where email_id ='$email_id' ";
    
        $result = mysqli_query($conn,$sql);
        $count = mysqli_num_rows($result);
    
        $to = "demo@gmail.com";
        $subject = "DEMO Subject";
        $messageBody ="demo message .";
    
        if($count ==0){
            $response["valid"] = false;
            $response["message"] = "User is not registered yet";
            echo json_encode($response);
            return;
        }
    
        else {
    
            $mail = new PHPMailer();
            $mail->IsSMTP();
            $mail->SMTPAuth = true; // authentication enabled
            $mail->IsHTML(true); 
            $mail->SMTPSecure = 'ssl';//turn on to send html email
            // $mail->Host = "ssl://smtp.zoho.com";
            $mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail 
            $mail->Port = 465;
            $mail->Username = "demousername@example.com";
            $mail->Password = "demopassword";
            $mail->SetFrom("demousername@example.com", "Any demo alert");
            $mail->Subject = $subject;
    
            $mail->Body = $messageBody;
            $mail->AddAddress($to);
            echo "yes";
    
            if(!$mail->send()) {
               echo "Mailer Error: " . $mail->ErrorInfo;
           } 
           else {
               echo "Message has been sent successfully";
          }
        }
    
    }
    else{
        $response["valid"] = false;
        $response["message"] = "Required field(s) missing";
        echo json_encode($response);
    }
    
    
    ?>
    

    上面的代码对我有用 .

  • 5

    您也可以在https://github.com/PHPMailer/PHPMailer使用PHPMailer类 .

    它允许您使用邮件功能或透明地使用smtp服务器 . 它还处理基于HTML的电子邮件和附件,因此您不必编写自己的实现 .

    该类是稳定的,它被许多其他项目使用,如Drupal,SugarCRM,Yii和Joomla!

    以下是上页中的示例:

    <?php
    require 'PHPMailerAutoload.php';
    
    $mail = new PHPMailer;
    
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'user@example.com';                 // SMTP username
    $mail->Password = 'secret';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted
    
    $mail->From = 'from@example.com';
    $mail->FromName = 'Mailer';
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');
    
    $mail->WordWrap = 50;                                 // Set word wrap to 50 characters
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
    $mail->isHTML(true);                                  // Set email format to HTML
    
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    
    if(!$mail->send()) {
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }
    
  • 1

    这是使用邮件功能发送纯文本邮件的非常基本的方法 .

    <?php
    $to = 'SomeOtherEmailAddress@Domain.com';
    $subject = 'This is subject';
    $message = 'This is body of email';
    $from = "From: FirstName LastName <SomeEmailAddress@Domain.com>";
    mail($to,$subject,$message,$from);
    

相关问题