使用Swift Mailer在PHP中发送电子邮件

在本文中,我们将探索Swift Mailer库,该库允许您从PHP应用程序发送电子邮件。 从安装和配置开始,我们将通过一个真实示例,演示使用Swift Mailer库发送电子邮件的各个方面。

什么是Swift Mailer?

在PHP应用程序中发送电子邮件时,您有很多选择。 您甚至可能最终创建自己的包装程序来快速设置电子邮件功能。 但是,如果您使用的是一个维护良好且功能丰富的库,那么您总是很幸运。

Swift Mailer是一个流行的库,用于从PHP应用程序发送电子邮件,并且已被PHP社区广泛接受。 从某种意义上说,它是一个功能丰富的库,它涵盖了发送电子邮件的几乎所有方面,从设置不同的传输方式到自定义要发送的消息。

实际上,使用Swift Mailer库发送电子邮件是一个非常简单的过程。

  1. 初始化传输(SMTP / Sendmail)对象。
  2. 使用该传输初始化Mailer对象。
  3. 初始化Message对象。
  4. 格式化并发送消息。

在下一节中,我们将通过一个实际示例演示上述每个步骤。

安装与配置

在本节中,我们将介绍Swift Mailer库的安装和配置。 安装非常简单,因为它已经作为Composer软件包提供。 在继续之前,请确保您已经安装Composer,因为我们需要它来安装Swift Mailer库。

安装Composer之后,继续使用以下命令获取Swift Mailer库。

$composer require "swiftmailer/swiftmailer:^6.0"

这样,应该安装Swift Mailer库,并在vendor目录中安装必要的依赖项。 新创建的composer.json的内容应如下所示:

{
    "require": {
        "swiftmailer/swiftmailer": "^6.0"
    }
}

这就是安装部分,但是您应该如何使用它呢? 实际上,只需要在应用程序中包含由Composer创建的autoload.php文件即可,如以下代码片段所示。

<?php
require_once './vendor/autoload.php';

// your application code...
?>

如何发送电子邮件

在上一节中,我们探讨了如何使用Composer安装Swift Mailer库。 在本节中,我们将开始实现一个实际示例。

继续并创建具有以下内容的email.php文件。

<?php
require_once './vendor/autoload.php';

try {
    // Create the SMTP Transport
    $transport = (new Swift_SmtpTransport('smtp.hostname', 25))
        ->setUsername('xxxxxxxx')
        ->setPassword('xxxxxxxx');

    // Create the Mailer using your created Transport
    $mailer = new Swift_Mailer($transport);

    // Create a message
    $message = new Swift_Message();

    // Set a "subject"
    $message->setSubject('Demo message using the SwiftMailer library.');

    // Set the "From address"
    $message->setFrom(['sender@gmail.com' => 'sender name']);

    // Set the "To address" [Use setTo method for multiple recipients, argument should be array]
    $message->addTo('recipient@gmail.com','recipient name');

    // Add "CC" address [Use setCc method for multiple recipients, argument should be array]
    $message->addCc('recipient@gmail.com', 'recipient name');

    // Add "BCC" address [Use setBcc method for multiple recipients, argument should be array]
    $message->addBcc('recipient@gmail.com', 'recipient name');

    // Add an "Attachment" (Also, the dynamic data can be attached)
    $attachment = Swift_Attachment::fromPath('example.xls');
    $attachment->setFilename('report.xls');
    $message->attach($attachment);

    // Add inline "Image"
    $inline_attachment = Swift_Image::fromPath('nature.jpg');
    $cid = $message->embed($inline_attachment);

    // Set the plain-text "Body"
    $message->setBody("This is the plain text body of the message.\nThanks,\nAdmin");

    // Set a "Body"
    $message->addPart('This is the HTML version of the message.<br>Example of inline image:<br><img src="'.$cid.'" width="200" height="200"><br>Thanks,<br>Admin', 'text/html');

    // Send the message
    $result = $mailer->send($message);
} catch (Exception $e) {
  echo $e->getMessage();
}

让我们看一下这段代码的工作方式。

初始化Swift Mailer

Swift Mailer库在发送电子邮件时支持SMTP和Sendmail等不同的传输方式。 因此,您需要做的第一件事是初始化transport对象。

在上面的示例中,我使用了SMTP传输来发送电子邮件。

$transport = (new Swift_SmtpTransport('smtp.hostname', 25))
    ->setUsername('xxxxxxxx')
    ->setPassword('xxxxxxxx');

当然,如果您想使用Sendmail协议,则需要初始化相应的Swift_SendmailTransport对象。

// Create the SendMail Transport
$transport = new Swift_SendmailTransport('/usr/sbin/sendmail -bs');

创建传输后,我们需要初始化一个邮件程序对象并传递已经创建的传输。

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
建立讯息

创建传输对象和邮件对象之后,剩下的唯一事情就是实例化Swift_Message对象并使用必要的属性对其进行修饰。

// Create a message
$message = new Swift_Message();

现在,我们将使用$message对象准备$message的内容。 首先,可以使用setSubject方法设置电子邮件的主题。

// Set a "subject"
$message->setSubject('Demo message using the SwiftMailer library.');

setFrom方法用于设置电子邮件的“发件人”地址。

// Set the "From address"
$message->setFrom(['sender@gmail.com' => 'Sender Name']);

继续,让我们设置电子邮件的“收件人”地址。 实际上,设置电子邮件的收件人有多种变体。 如果你想设置一个收件人,您可以使用addTo方法和setTo方法,而另一方面,用于设置多个收件人。

// Set the "To address" [Use setTo method for multiple recipients, argument should be array]
$message->addTo('recipient@gmail.com','receiver name');

addCcaddBcc方法分别用于设置电子邮件的抄送和密件抄送地址。

// Add "CC" address [Use setCc method for multiple recipients, argument should be array]
$message->addCc('recipient@gmail.com', 'recipient name');

// Add "BCC" address [Use setBcc method for multiple recipients, argument should be array]
$message->addBcc('recipient@gmail.com', 'recipient name');
附加文件

接下来,让我们看看如何将文件附加到电子邮件。

首先,您需要使用有效的文件名实例化Swift_Attachment对象。 创建附件对象后,可以使用attach方法将其添加到电子邮件中。 另外,如果要更改将显示在邮件附件中的文件名,则可以使用setFilename方法。

// Add an "Attachment" (Also, the dynamic data can be attached)
$attachment = Swift_Attachment::fromPath('example.xls');
$attachment->setFilename('report.xls');
$message->attach($attachment);

连同常规文件附件一起,有时您希望将图像嵌入消息文本中。 您可以使用embed方法执行此操作,如以下代码片段所示。 embed方法返回嵌入对象的唯一ID,您可以稍后在消息中使用该ID,同时通过src属性引用该图像。

// Add inline "Image"
$inline_attachment = Swift_Image::fromPath('nature.jpg');
$cid = $message->embed($inline_attachment);
消息正文

接下来,让我们使用setBody方法设置电子邮件正文。

// Set the plain-text "Body"
$message->setBody("This is the plain text body of the message.\nThanks,\nAdmin");

如果要设置消息HTML版本,则可以使用addPart方法,如以下代码片段所示。 如您所见,我们使用$cid引用我们之前嵌入的图像。

// Set a "Body"
$message->addPart('This is the HTML version of the message.<br>Example of inline image:<br><img src="'.$cid.'" width="200" height="200"><br>Thanks,<br>Admin', 'text/html');
发送信息!

最后,我们将使用Mailer对象的send方法发送电子邮件。

// Send the message
$result = $mailer->send($message);

尝试运行脚本,您应该会收到一封电子邮件! 如果您遇到任何问题,请在评论部分让我知道。

结论

今天,我们研究了用于发送电子邮件的最受欢迎的PHP库之一:Swift Mailer。 使用此库,您可以轻松地从PHP脚本发送电子邮件。

请使用以下表格随意发表您的想法和疑问。

翻译自: https://code.tutsplus.com/tutorials/send-emails-in-php-using-the-swift-mailer--cms-31218

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值