要使用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郵件。