在 PHP 中,使用 SwiftMailer 库发送带有附件的电子邮件是一个相对简单的过程。以下是一个示例代码,展示了如何使用 SwiftMailer 发送带有附件的电子邮件:
首先,确保已经安装了 SwiftMailer 库。如果还没有安装,可以通过 Composer 安装:composer require swiftmailer/swiftmailer然后,创建一个 PHP 文件(例如 send_email_with_attachment.php),并在其中编写以下代码:<?php// 引入 SwiftMailer 的自动加载器require_once 'vendor/autoload.php';// 创建一个新的 Swift_Message 实例$message = (new Swift_Message('邮件主题')) ->setFrom(['your_email@example.com' => 'Your Name']) ->setTo(['recipient@example.com' => 'Recipient Name']) ->setBody('这是一封带有附件的邮件。');// 添加附件$attachment = Swift_Attachment::fromPath('path/to/your/attachment.ext');$message->attach($attachment);// 配置 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);if ($result) { echo "邮件发送成功!";} else { echo "邮件发送失败!";}请确保将上述代码中的以下内容替换为您自己的信息:your_email@example.com:您的发件人电子邮件地址Your Name:您的名字或发件人别名recipient@example.com:收件人电子邮件地址Recipient Name:收件人名字或别名path/to/your/attachment.ext:附件的路径和文件名smtp.example.com:SMTP 服务器地址your_email_password:您的电子邮件密码最后,运行 PHP 文件以发送带有附件的电子邮件:php send_email_with_attachment.php如果一切正常,您应该会看到“邮件发送成功!”的消息。收件人应该会收到一封带有附件的电子邮件。


