透過PHPMailer來發送電郵

  • 下載PHPMailer

下載套件及解壓縮

https://github.com/PHPMailer/PHPMailer

  • Import 相關檔案
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
include "PHPMailer/Exception.php";
include "PHPMailer/PHPMailer.php";
include "PHPMailer/SMTP.php";
  • 設定SMTP
<?php
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; //SMTP服務器
$mail->Port = 465; //SSL預設Port 是465, TLS預設Port 是587
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //使用SSL, 如果是TLS 請改為 PHPMailer::ENCRYPTION_STARTTLS
$mail->Username = "your.gmail.name"; // 這裡填寫你的SMTP登入帳號, 例如 [email protected] 則填寫your.gmail.name
$mail->Password = "your_password"; //這裡填寫你的SMTP登入密碼. 即是Gmail的密碼
  • 設定電郵的內容
<?php
$mail->From = "[email protected]"; //設定寄件人電郵
$mail->FromName = "sender name"; //設定寄件人名稱
$mail->Subject = "This is my test email"; //設定郵件主題
$mail->Body = "This is email body";  //設定郵件內容
$mail->IsHTML(true);  //設定是否使用HTML格式
$mail->addAddress("[email protected]", "person A"); //設定收件人電郵及名稱
$mail->addAddress("[email protected]", "person B"); //同上
$mail->addCC("[email protected]", "person C"); //設定收件人電郵及名稱(CC)
$mail->addBCC("[email protected]", "person D"); //設定收件人電郵及名稱(BCC)
$mail->addAttachment("image1.jpg", "picture.jpg"); //設定附件, 對方會看到附件名稱為 picture.jpg
if(!$mail->Send()){
  echo "Mailer error: " . $mail->ErrorInfo;
}
else{
  echo "Email sent";
}
Scroll to Top