Gmail 需啟用「兩步驟驗證」並產生「應用程式密碼」,並支援 SSL (465) 與 TLS (587) 兩種模式。
<?php
require_once '../class.phpmailer.php';
$mail = new PHPMailer();
$mail->CharSet = 'utf-8';
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_account@gmail.com';
$mail->Password = 'your_app_password'; // 應用程式密碼
$mail->SMTPSecure = 'ssl'; // 或 'tls'
$mail->Port = 465; // SSL=465, TLS=587
$mail->SMTPDebug = 2; // 除錯輸出
$mail->setFrom('your_account@gmail.com', 'First Last');
$mail->addReplyTo('your_account@gmail.com', 'First Last');
$mail->addAddress('recipient@example.com', 'John Doe');
$mail->isHTML(true);
$mail->Subject = 'PHPMailer Gmail SMTP Test';
$mail->Body = file_get_contents('contents.html'); // 讀取外部 HTML 模板
$mail->AltBody = '請使用 HTML 郵件用戶端檢視。';
// 加入附件
$mail->addAttachment('images/phpmailer.gif');
$mail->addAttachment('images/phpmailer_mini.gif');
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message sent!';
}
?>
SMTPSecure = 'tls' 並確認伺服器支援 STARTTLS。SMTPDebug = 2 可輸出詳細 SMTP 交互過程,除錯時極有幫助。