使用 PHP 透過 SMTP 服務寄送電子郵件

前言

本文使用 Gmail 提供的 SMTP server 做為範例。

設定

首先,到 Google 帳戶的「安全性」頁面,設定以下:

  • 啟用兩步驟驗證(2-Step Verification)
  • 新增應用程式密碼(App passwords)

實作

建立專案。

1
2
mkdir smtp-php-example
cd smtp-php-example

建立 .gitignore 檔。

1
2
vendor
.env

初始化專案。

1
composer init

修改 composer.json 檔。

1
2
3
4
{
"name": "memochou1993/smtp-php-example",
"require": {}
}

安裝依賴套件。

1
composer require phpmailer/phpmailer vlucas/phpdotenv

新增 .env 檔。

1
2
3
4
5
6
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your-email
SMTP_PASSWORD=your-application-password
SMTP_FROM=your-email
SMTP_FROM_NAME=your-name

新增 index.php 檔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

function sendExampleEmail(string $to, string $subject, string $body): bool
{
$mail = new PHPMailer(true);

try {
$mail->isSMTP();
$mail->Host = $_ENV['SMTP_HOST'];
$mail->Port = $_ENV['SMTP_PORT'];
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPAuth = true;
$mail->Username = $_ENV['SMTP_USERNAME'];
$mail->Password = $_ENV['SMTP_PASSWORD'];
$mail->setFrom($_ENV['SMTP_FROM'], $_ENV['SMTP_FROM_NAME']);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->isHTML(true);
$mail->Body = $body;
$mail->send();
return true;
} catch (Exception $e) {
error_log("Email failed: {$mail->ErrorInfo}");
return false;
}
}

$to = 'memochou1993@gmail.com';
$subject = 'This is an example email';
$body = '<html><body><h1>Hello, this is an <b>HTML</b> email!</h1><p>This is the body of the email in HTML format.</p></body></html>';

if (sendExampleEmail($to, $subject, $body)) {
echo "Email sent successfully.";
} else {
echo "Email failed.";
}

寄送郵件。

1
php index.php

程式碼