php發送郵件

此文是對慕課網中這一課程的筆記。

一 首先是使用 telnet 命令發送郵件,此處用的郵箱爲阿里郵箱和新浪郵箱。

C:\Users\Administrator>telnet smtp.aliyun.com 25
220 smtp.aliyun.com MX AliMail Server(127.0.0.1)
helo hi    //測試是否連接成功
250 Ok
auth login      //開始身份認證
334 dXNlcm5hbWU6     //334說明成功
"郵箱地址的base64編碼" UGFzc3dvcmQ6   
"郵箱密碼的base64編碼: Authentication successful   //提示 successful 說明登錄成功
mail from: <[email protected]>   //發件人郵件
250 Mail Ok
rcpt to:<[email protected]>     //收件人郵箱
250 Rcpt Ok
data      //開始寫郵件正文
354 End data with <CR><LF>.<CR><LF>   // 354說明成功
from: aliyun      //郵件中顯示發件人
to: sina          //郵件中顯示的收件人
subject: this is a demo show    //郵件中顯示的主題,之後按兩個回車

this is a email content     //輸入文章的內容,之後按回國
.                      //再輸入.,回車
250 Data Ok: queued as freedom     //提示250,說明郵件已發送成功

二 使用第三方庫發送郵件
下載地址:https://github.com/PHPMailer/PHPMailer/
以下爲作者寫的一個簡單的例子:

<?php
$rootPath = dirname(__FILE__);
require '..\PHPMailer-master\PHPMailerAutoload.php';   //引用包

$mail = new PHPMailer;

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

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.aliyun.com';  // smtp 服務器地址
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->CharSet = "UTF-8";        //郵件內容編碼
$mail->Username = '[email protected]';                 // SMTP username
$mail->Password = 'password';                           // SMTP password
// $mail->SMTPSecure = 'tls';                            // 加密方式
// $mail->Port = 587;                                    // TCP port to connect to

$mail->setFrom('[email protected]', 'aliyun');
$mail->addAddress('[email protected]', 'sina');     // Add a recipient
$mail->addReplyTo('[email protected]', 'Information');    //收件人回覆的郵件地址
$mail->addCC('[email protected]');             //抄送,需要時設置
$mail->addBCC('[email protected]');           //密送,需要時設置

// $mail->addAttachment('/var/tmp/file.tar.gz');         // 發送附件
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // 郵件正文使用html格式

$mail->Subject = 'Here is the subject with file';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';       //正文信息(html文檔格式)
// $mail->msgHTML(file_get_contents("file.html"));  //從 html 文檔中讀取內容併發送(以 html 文檔格式)
// $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';     // 未帶html的內容

// 如果郵件發送失敗,輸出錯誤信息
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章