標籤:
一般註冊一個新的帳號,都會收到一封官方的郵件,那麼如何為自己的項目建立自動發送郵件的系統呢?
一、擁有自己的郵箱帳號,以163郵箱為例。
二、開啟用戶端授權碼,只有開啟之後才能通過PHP代碼,控制郵件的自動發送。
在PHP中,需要使用的密碼就是,開啟郵箱用戶端授權後設定的密碼。
三、PHPMailer的下載
:https://github.com/PHPMailer/PHPMailer
github上有相關的使用說明
郵件發送代碼如下:
require ‘PHPMailerAutoload.php‘; //載入需要使用的類, 或者使用:include("class.phpmailer.php"); include("class.smtp.php");$mail = new PHPMailer;//$mail->SMTPDebug = 3; // Enable verbose debug output$mail->isSMTP(); // Set mailer to use SMTP$mail->Host = ‘smtp1.example.com‘; // Specify main and backup SMTP servers 設定郵箱伺服器,根據自己郵箱的類型而不同,比如163郵箱: $mail->Host = "smtp.163.com";$mail->SMTPAuth = true; // Enable SMTP authentication$mail->Username = ‘[email protected]‘; // SMTP username 你自己的郵箱帳號$mail->Password = ‘secret‘; // SMTP password 你自己的帳號密碼$mail->SMTPSecure = ‘tls‘; // Enable TLS encryption, `ssl` also accepted 郵箱伺服器所使用的機密協議 163郵箱可以注釋此項$mail->Port = 587; // TCP port to connect to 163郵箱伺服器連接埠為: 25$mail->setFrom(‘[email protected]‘, ‘Mailer‘);$mail->addAddress(‘[email protected]‘, ‘Joe User‘); // 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‘;}
四、郵件資訊亂碼問題的解決:
a.解決非標題漢字亂碼
在PHPMailer 庫檔案class.phpmailer.php中,
找到 public $CharSet = ‘iso-8859-1‘;
改成 public $CharSet = ‘UTF-8‘;
並且 把檔案儲存為UTF-8格式。
b.解決標題漢字亂碼
$mail->Subject ="=?utf-8?B?" . base64_encode(" 你的標題內容 ") . "?=";
php實現郵件自動發送之PHPMailer