推荐答案
// www.javascriptcn.com code example
// 使用 PHPMailer 发送邮件
require 'vendor/autoload.php'; // 引入 Composer 自动加载文件
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
// 服务器设置
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// 收件人
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('to@example.com', 'Recipient Name');
// 内容
$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';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}// www.javascriptcn.com code example
// 使用 SwiftMailer 发送邮件
require 'vendor/autoload.php'; // 引入 Composer 自动加载文件
use Swift_SmtpTransport;
use Swift_Mailer;
use Swift_Message;
// 创建传输器
$transport = (new Swift_SmtpTransport('smtp.example.com', 587, 'tls'))
->setUsername('your_email@example.com')
->setPassword('your_password');
// 创建邮件器
$mailer = new Swift_Mailer($transport);
// 创建消息
$message = (new Swift_Message('Here is the subject'))
->setFrom(['from@example.com' => 'Mailer'])
->setTo(['to@example.com' => 'Recipient Name'])
->setBody('This is the HTML message body <b>in bold!</b>', 'text/html')
->addPart('This is the body in plain text for non-HTML mail clients', 'text/plain');
// 发送邮件
$result = $mailer->send($message);
if ($result) {
echo 'Message has been sent';
} else {
echo 'Message could not be sent';
}本题详细解读
PHPMailer 使用步骤
- 引入依赖:通过 Composer 安装 PHPMailer 并引入自动加载文件。
- 创建实例:实例化
PHPMailer 类。
- 配置 SMTP:设置 SMTP 服务器、认证信息、加密方式和端口。
- 设置发件人和收件人:使用
setFrom 和 addAddress 方法设置发件人和收件人。
- 设置邮件内容:设置邮件主题、HTML 内容和纯文本内容。
- 发送邮件:调用
send 方法发送邮件,并捕获异常处理错误。
SwiftMailer 使用步骤
- 引入依赖:通过 Composer 安装 SwiftMailer 并引入自动加载文件。
- 创建传输器:使用
Swift_SmtpTransport 配置 SMTP 服务器、端口、加密方式、用户名和密码。
- 创建邮件器:使用
Swift_Mailer 类创建邮件器实例。
- 创建消息:使用
Swift_Message 类创建邮件消息,设置发件人、收件人、主题、HTML 内容和纯文本内容。
- 发送邮件:调用
send 方法发送邮件,并根据返回值判断是否发送成功。
注意事项
- SMTP 配置:确保 SMTP 服务器地址、端口、加密方式、用户名和密码正确。
- 异常处理:在使用 PHPMailer 时,建议使用
try-catch 捕获异常,以便处理发送失败的情况。
- 依赖管理:推荐使用 Composer 管理 PHP 项目的依赖,确保库的版本兼容性。