2016年3月4日 星期五

PHPMailer 用 PHP 發信 & Gmail 申請應用程式密碼

在 github 上面有一個 PHPMailer 專案,他號稱是目前世界上最潮的 PHP send mail code production,對於編碼的支援度也很好,最重要的是他支援各種驗證機制,這讓很多目前五花八門的驗證方式相容性就提高了許多

 

Class Features

Probably the world's most popular code for sending email from PHP!
Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla! and many more
Integrated SMTP support - send without a local mail server
Send emails with multiple TOs, CCs, BCCs and REPLY-TOs
Multipart/alternative emails for mail clients that do not read HTML email
Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings
SMTP authentication with LOGIN, PLAIN, NTLM, CRAM-MD5 and Google's XOAUTH2 mechanisms over SSL and TLS transports
Error messages in 47 languages!
DKIM and S/MIME signing support
Compatible with PHP 5.0 and later
Much more!



 

在此篇簡單紀錄如何使用 PHPMailer

Step.1 複製 PHPMailer 專案
$ git clone https://github.com/PHPMailer/PHPMailer

 

Step.2 建立單封郵件測試
$ cd PHPMailer 
$ sendmail.php

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

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

// Set mailer to use SMTP
$mail->isSMTP();

// smtp 伺服器, 支援多台smtp server備援
$mail->Host = 'smtp1.gmail.com';

// Enable SMTP authentication
$mail->SMTPAuth = true;

// SMTP username
$mail->Username = 'user@example.com';

// SMTP password , If you must use the gmail application password
$mail->Password = 'secret';

// Enable TLS encryption, `ssl` also accepted
$mail->SMTPSecure = 'tls';

// TCP port to connect to
$mail->Port = 587;

$mail->setFrom('from@example.com', 'Mailer');

// Add a recipient , name is optional
$mail->addAddress('joe@example.net', 'Joe User');
$mail->addAddress('ellen@example.com');

// Add a recipient ,
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

// Add attachments , optional name
$mail->addAttachment('/var/tmp/file.tar.gz');
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');

// Set email format to HTML
$mail->isHTML(true);

$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';
}

 

如果你使用的是 Gmail smtp,那 Password 的部分如果你使用的是 "網頁登入的密碼" 就會被 Gmail 阻擋顯示錯誤訊息『Please log in via your web browser and then try again.』,並且要求使用 application password

 

 

申請 Gmail Application Password

登入你的 Gmail 到以下找到應用程式密碼進行新增,Gmail 會提供一組密碼給你作應用程式驗證使用。

https://myaccount.google.com/u/0/security

ScreenShot 2016-03-03 17.58.11

將密碼代入 send.php 中的 $mail->Password 就可以驗證成功!

 

 

 

 

Orignal From: PHPMailer 用 PHP 發信 & Gmail 申請應用程式密碼

沒有留言:

張貼留言