1. 程式人生 > >基於php5.5使用PHPMailer-5.2傳送郵件

基於php5.5使用PHPMailer-5.2傳送郵件

PHPMailer - A full-featured email creation and transfer class for PHP。

在PHP環境中可以使用PHPMailer來建立和傳送郵件。

最新版本(20181012)是PHPMailer 6.0.5,這個無法相容php5.5以下的環境。由於我需要維護 php5.3的專案,需要切換到PHPMailer5.2來發送郵件。

下載地址: https://github.com/PHPMailer/PHPMailer/releases/tag/v5.2.24

基本使用

下載解壓後。新建一個測試demo。

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.exmail.qq.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '
[email protected]
'; // SMTP username $mail->Password = 'yourpassword'; // SMTP password $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 465; // TCP port to connect to $mail->setFrom('
[email protected]
', 'Mailer'); $mail->addAddress('[email protected]', 'Ryan Miao'); // Add a recipient $mail->addAddress('[email protected]'); // Name is optional // $mail->addReplyTo('[email protected]', 'Information'); $mail->addCC('[email protected]'); $mail->addBCC('
[email protected]
'); $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'; }

開啟SMTPDebug可以檢視日誌

 `0` No output
 `1` Commands
 `2` Data and commands
 `3` As 2 plus connection status
 `4` Low-level data output

錯誤資訊儲存在 $mail->ErrorInfo物件中。

儲存為mail.php, 命令列執行

php mail.php

即可看到日誌,以及郵件傳送成功。