PHP邮件发送库:Swiftmailer
2025-09-23 17:24
Swift
188
0
0
0
标题录入
封面图
SwiftMailer 是一个功能强大、灵活且广泛使用的 PHP 邮件发送库。它提供了丰富的功能,包括支持 SMTP、邮件模板、附件、HTML 邮件、多语言支持等。 --- ## 📦 一、安装 SwiftMailer 你可以使用 Composer 来安装 SwiftMailer: ```bash composer require swiftmailer/swiftmailer ``` 或者手动下载 [SwiftMailer 官方 GitHub 仓库](https://github.com/swiftmailer/swiftmailer) 并引入相关文件。 --- ## 🚀 二、基本用法示例 以下是一个简单的 PHP 示例,演示如何使用 SwiftMailer 发送一封电子邮件: ```php <?php require_once 'vendor/autoload.php'; use Swift_Mailer; use Swift_SmtpTransport; use Swift_Message; // 创建 SMTP 传输器(以 Gmail 为例) $transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls')) ->setUsername('your-email@gmail.com') ->setPassword('your-app-password'); // 使用应用专用密码 // 创建邮件发送器 $mailer = new Swift_Mailer($transport); // 创建消息对象 $message = (new Swift_Message('主题:测试邮件')) ->setFrom(['your-email@gmail.com' => 'Your Name']) ->setTo(['recipient@example.com' => 'Recipient Name']) ->setBody('这是一封测试邮件内容。') // 可选:添加 HTML 内容 // ->setBody('<h1>HTML 邮件标题</h1><p>这是 HTML 格式的邮件内容。</p>', 'text/html') // 可选:添加附件 // ->attach(Swift_Attachment::fromPath('path/to/file.pdf')->setFilename('document.pdf')); // 发送邮件 $result = $mailer->send($message); if ($result > 0) { echo "邮件发送成功!"; } else { echo "邮件发送失败。"; } ``` --- ## ✅ 三、常见功能说明 ### 1. **HTML 邮件** ```php $message->setBody('<h1>欢迎!</h1><p>感谢注册。</p>', 'text/html'); ``` ### 2. **添加附件** ```php $message->attach(Swift_Attachment::fromPath('file.txt')->setFilename('file.txt')); ``` ### 3. **设置回复地址** ```php $message->setReplyTo(['reply@example.com' => 'Reply Name']); ``` ### 4. **设置多个收件人** ```php $message->setTo([ 'user1@example.com' => 'User One', 'user2@example.com' => 'User Two' ]); ``` ### 5. **设置 BCC(密送)** ```php $message->setBcc(['bcc@example.com' => 'BCC User']); ``` --- ## 🧩 四、SMTP 配置示例 | 邮件服务 | SMTP 主机 | 端口 | 加密方式 | |----------|-----------|------|----------| | Gmail | smtp.gmail.com | 587 | tls | | Outlook | smtp.office365.com | 587 | tls | | QQ 邮箱 | smtp.qq.com | 465 或 587 | ssl 或 tls | | 163 邮箱 | smtp.163.com | 465 | ssl | --- ## 🛡️ 五、安全建议 - **使用应用专用密码**(如 Gmail):避免直接使用账户密码。 - **开启 SMTP 身份验证**:确保只有授权用户可以发送邮件。 - **限制发送频率**:防止被误认为垃圾邮件。 --- ## 📘 六、文档与资源 - [SwiftMailer 官方文档](https://swiftmailer.symfony.com/docs/) - [GitHub 项目地址](https://github.com/swiftmailer/swiftmailer) --- 如果你有具体的使用场景(比如发送 HTML 邮件、带附件、使用不同的 SMTP 服务器等),我可以为你提供更详细的代码示例。需要吗?
标题录入,一次不能超过6条
区块链
T:0.007608s,M:116.26 KB
返回顶部
留言
留言
评论