教學目的主要有兩個
- 讓用家掌握使用終端(Terminal)及Composer的流程
-了解SMTP設定
為何需要phpmailer發送電郵?
近年垃圾電郵問題越趨嚴重,相對的主要電郵服務商如Yahoo跟Google一直在提高一些返垃圾電郵(Anti-spam)的要求。這個情況下單純使用php sendmail發送電郵很容易會被錯誤辨識為垃圾郵件,又或者需要複雜的Email Header設定才能達到成功送達效果,而phpmailer就是其中一個簡單的解決方案。
1) 首先登入Directadmin網上控制台,進入"系統資訊和檔案" > "終端"
2) 先進入public_html 資料夾(假設php script需要公開),然後輸入安裝指令composer require phpmailer/phpmailer
3) 安裝完成後,可以參考以下示範
(源始碼來自 https://github.com/PHPMailer/PHPMailer )
4) 特別留意源始碼的登入設定,包括
$mail->Host = 'mail.floppy-demo.com';
如果使用Gmail發送電郵,主機名稱應該是smtp.gmail.com
$mail->Username = '[email protected]';
$mail->Password = 'PASSWORD';
如果使用Gmail發送電郵,電郵密碼應該是App Password,不懂如果取得可參考這個教學。
$mail->setFrom('[email protected]', '寄件者名稱');
寄件者電郵地址必須跟用家使用的SMTP帳號相關,例如不能SMTP用GMAIL的,但寄件電郵地址用科比的,反之亦然。
<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'vendor/autoload.php';
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'mail.floppy-demo.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = '[email protected]'; //SMTP username
$mail->Password = 'PASSWORD'; //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
$mail->Port = 465; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//Recipients
$mail->setFrom('[email protected]', '寄件者名稱');
$mail->addAddress('[email protected]', '收件者名稱'); //Add a recipient
//Content
$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';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}