要使用PHP SwiftMailer库发送HTML邮件,请按照以下步骤操作:
composer require swiftmailer/swiftmailer
require_once 'vendor/autoload.php';
$message = (new Swift_Message('邮件主题'))
->setFrom(['sender@example.com' => '发件人名称'])
->setTo(['recipient@example.com' => '收件人名称']);
$htmlContent = '<h1>Hello, World!</h1><p>这是一封HTML邮件。</p>';
$message->setBody($htmlContent, 'text/html');
$transport = (new Swift_SmtpTransport('smtp.example.com', 587))
->setUsername('your_email@example.com')
->setPassword('your_email_password');
$mailer = new Swift_Mailer($transport);
$result = $mailer->send($message);
将上述代码片段整合到一起,完整示例如下:
<?php
require_once 'vendor/autoload.php';
// 创建Swift_Message实例并设置基本信息
$message = (new Swift_Message('邮件主题'))
->setFrom(['sender@example.com' => '发件人名称'])
->setTo(['recipient@example.com' => '收件人名称']);
// 添加HTML内容
$htmlContent = '<h1>Hello, World!</h1><p>这是一封HTML邮件。</p>';
$message->setBody($htmlContent, 'text/html');
// 配置SMTP传输器
$transport = (new Swift_SmtpTransport('smtp.example.com', 587))
->setUsername('your_email@example.com')
->setPassword('your_email_password');
// 创建Swift_Mailer实例并发送邮件
$mailer = new Swift_Mailer($transport);
$result = $mailer->send($message);
echo "邮件发送成功!";
?>
根据实际情况修改发件人、收件人、SMTP服务器等相关信息,然后运行此脚本即可发送HTML邮件。