PHP发邮件的几种方式总结

2017-04-29

第一类,使用php内置的mail()函数。

这是php内置的函数,看文档感觉此函数用起来十分简单。确实,用起来非常简单,但是要用此函数,需要在本机配置一个sendmail服务器,这么看来,就不是那么简单了。

mail()函数用法:

<?php
// The message
$message = "Line 1\nLine 2\nLine 3";

// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70);

// Send
mail('caffinated@example.com', 'My Subject', $message);
?>

第二类,利用第三方类库

相比与第一类,我相信第二类是很多人的选择。
因为无需再配置什么,直接拿来用,而且开发环境不一定允许你配置。
这一类的类库,往往需要依托一个第三方的邮件服务器,例如,163邮箱,qq邮箱,sina邮箱等等

PHPMailer

此类库是目前github上星最多的第三方库,本人强烈推荐此类库。github地址是:https://github.com/PHPMailer/PHPMailer
使用方法很简单:

  • 使用composer,在composer.json中加入:

    "phpmailer/phpmailer": "~5.2"

    或者是5.2之外的其他版本。也可以使用

    composer require phpmailer/phpmailer
  • 以163邮箱为例,去设置一个登陆163邮箱的授权码。具体设置请看: http://jingyan.baidu.com/article/1876c8526895ce890b1376b1.html

  • 按照如下例子,就可以发邮件了

    <?php
    require 'PHPMailerAutoload.php';
    
    $mail = new PHPMailer;
    
    //$mail->SMTPDebug = 3;                               // Enable verbose debug output
    
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.163.com';                         // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'user@163.com';                 // SMTP username
    $mail->Password = 'secret';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    
    $mail->setFrom('from@example.com', '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->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';
    }

SwiftMailer

这个邮件类库也很强大,虽然星星不算太多,但是却是PHP 杀手级框架Laravel所内置的邮件类库,可见其威力。
就目前而言,此类库官方强调的是只支持php5.x的版本,至于说为什么在使用php7.0 的 laravel框架下可用(亲身经历),暂时不可知。
此类库的使用方法:

  • 如果是使用composer,SwiftMailer将会被自动安装。github地址:https://github.com/swiftmailer/swiftmailer
    如果不是时候用composer,你需要引入swift_required.php文件。(类库文件可以从GitHub中找到)

    require_once '/path/to/swift-mailer/lib/swift_required.php';
    
    /* rest of code goes here */
  • 以163邮箱为例,去设置一个登陆163邮箱的授权码。具体设置请看: http://jingyan.baidu.com/article/1876c8526895ce890b1376b1.html

  • 按照如下代码,就可以发邮件了:

     require_once 'lib/swift_required.php';
    
     // Create the Transport
     $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
          ->setUsername('your username')
          ->setPassword('your password');
    
    /*
    You could alternatively use a different transport such as Sendmail or Mail:
    
    // Sendmail
    $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
    
    // Mail
    $transport = Swift_MailTransport::newInstance();
    */
    
    // Create the Mailer using your created Transport
    $mailer = Swift_Mailer::newInstance($transport);
    
    // Create a message
    $message = Swift_Message::newInstance('Wonderful Subject')
      ->setFrom(array('john@doe.com' => 'John Doe'))
      ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
      ->setBody('Here is the message itself');
    
    // Send the message
    $result = $mailer->send($message);