mailer deamon
Sending emails programmatically is a common task that programmers must deal with often. Although you can use PHP’s native functions, they can be too low-level, especially when you want to attach one or more files to your message. If you don’t want to use the native functions, or if you want to send mail using an object-oriented approach, then this is the article for you. I’ll introduce you to Swift Mailer, a powerful component-based library that let’s you send emails easily.
以编程方式发送电子邮件是程序员必须经常处理的一项常见任务。 尽管您可以使用PHP的本机函数,但是它们的级别可能太低,尤其是当您要将一个或多个文件附加到消息中时。 如果您不想使用本机函数,或者您想使用面向对象的方法发送邮件,那么本文适合您。 我将向您介绍Swift Mailer,它是一个功能强大的基于组件的库,可让您轻松发送电子邮件。
Started in 2005, Swift Mailer is a library that provides several classes that allow you to send emails from within your PHP scripts or web applications. Swift Mailer has some requirements, however they’re minimal; the library needs PHP 5.2 or higher with the SPL extension and a minimum memory limit of 8MB.
Swift Mailer始于2005年,是一个提供多个类的库,使您可以从PHP脚本或Web应用程序中发送电子邮件。 Swift Mailer有一些要求,但是要求很少。 该库需要PHP 5.2或更高版本以及SPL扩展名,最小内存限制为8MB。
Citing the official documentation, installing Swift Mailer is trivial. Usually it’s just a case of uploading the extracted source files to your web server. The simplest way to install the library is through PEAR or uploading the files using an FTP.
引用官方文档 ,安装Swift Mailer很简单。 通常,这只是将提取的源文件上传到Web服务器的一种情况。 安装库的最简单方法是通过PEAR或使用FTP上传文件。
Installing from the PEAR channel is just a matter of type two commands:
从PEAR通道进行安装仅需通过两种命令即可:
pear channel-discover pear.swiftmailer.org
pear install swift/swift
The second method is probably the easiest one if you’re on a shared hosting and you don’t have access to the command shell. Just download the library from the official website and upload the lib
folder.
第二种方法可能是最简单的方法,如果您位于共享主机上并且没有访问命令外壳的权限。 只需从官方网站下载库并上传lib
文件夹。
Swift Mailer is made of more than 150 classes and interfaces grouped together in several components. Each of them have a specific purpose.
Swift Mailer由150多个类和接口组成,这些类和接口分为多个组件。 他们每个人都有特定的目的。
Mailer: The mailer, which is realized by the Swift_Mailer
class, is the central class in the library and the one that actually sends the email through the method send()
. Its constructor accepts an instance of a class that implements the interface Swift_Transport
which allows you to send email using a custom SMTP.
Mailer :mailer是由Swift_Mailer
类实现的,它是库中的中心类,也是通过send()
方法实际发送电子邮件的类。 其构造函数接受实现接口Swift_Transport
的类的实例,该接口允许您使用自定义SMTP发送电子邮件。
Transporters: They implement the interface Swift_Transport
and their scope is to communicate with a service to deliver an email message. The main classes are Swift_SmtpTransport
which uses the SMTP protocol, Swift_SendmailTransport
which communicates with a local sendmail executable, and Swift_MailTransport
that relies on the PHP native mail()
function.
运输者 :它们实现了Swift_Transport
接口,其范围是与服务进行通信以传递电子邮件。 主要类是Swift_SmtpTransport
其使用SMTP协议, Swift_SendmailTransport
其与当地的sendmail可执行通信,并且Swift_MailTransport
它依赖于PHP本地mail()
函数。
MIME Entities: This is a key component in the library. The class you’ll use to specify the receiver, the subject, the body and so on, called Swift_Message
is made of several entities that are grouped together. Two example of entities are the attachments and the email header.
MIME实体 :这是库中的关键组件。 您将用于指定接收方,主题,正文等的类,称为Swift_Message
是由几个实体组成的,这些实体被分组在一起。 实体的两个示例是附件和电子邮件标题。
Encoders: This component isn’t something you’ll deal with because it acts behind the scenes. There are two types of Encoders: Base64 and Quoted-Printable. Their goal is to transform the contents into a format that conforms to RFC specifications.
编码器 :这个组件不是您要处理的,因为它在幕后起作用。 编码器有两种类型:Base64和Quoted-Printable。 他们的目标是将内容转换为符合RFC规范的格式。
Plugins: These are used to extend Swift Mailer’s basic functionality. Some of the plugins are AntiFlood, which allows you to limit the number of messages sent during a single SMTP connection, Logger, used to log what’s going on during the send process, and Decorator, an amazing plugin that allows you to use an email template and change just a few differences in the email text.
插件 :这些插件用于扩展Swift Mailer的基本功能。 其中一些插件是AntiFlood(可用于限制单个SMTP连接期间发送的邮件数量),Logger(用于记录发送过程中发生的情况)和Decorator(令人惊叹的插件,可让您使用电子邮件模板)并仅更改电子邮件文本中的一些区别。
With me so far? Good. Now that you’ve got an idea of how the components are organized in the library, let’s get our hands dirty and see how to take advantage of the power and flexibility of Swift Mailer. In this first and very simple example, I’ll show you the creation of an email that has two recipients, a subject, and a plain-text body. Once created, it’ll be sent to the recipients.
到目前为止和我在一起? 好。 现在您已经了解了库中组件的组织方式,让我们动手做一下,看看如何利用Swift Mailer的强大功能和灵活性。 在这个第一个非常简单的示例中,我将向您展示具有两个收件人,一个主题和一个纯文本正文的电子邮件的创建。 创建完成后,它将发送给收件人。
The following code uses three of the classes mentioned in the previous section: Swift_MailTransport
, Swift_Mailer
and Swift_Message
. In addition, note the first line of the code, the require_once
which pulls in Swift Mailer’s autoloader which is needed to use the library.
以下代码使用上一节中提到的三个类: Swift_MailTransport
, Swift_Mailer
和Swift_Message
。 另外,请注意代码的第一行, require_once
,它拉入使用该库所需的Swift Mailer的自动加载器。
<?php
require_once 'lib/swift_required.php';
// Create the mail transport configuration
$transport = Swift_MailTransport::newInstance();
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
"hello@gmail.com" => "Aurelio De Rosa",
"test@fake.com" => "Audero"
));
$message->setSubject("This email is sent using Swift Mailer");
$message->setBody("You're our best client ever.");
$message->setFrom("account@bank.com", "Your bank");
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);
As you can see, Swift_MailTransport
is used to create an instance of a transport layer which will use the native PHP mail()
function. Then I created a Swift_Message
instance which you can think of as the email object. In the following lines I set the recipients using the setTo()
method, the email subject using setSubject()
, the email body using setBody()
, and the sender using the setFrom()
method. With the layer defined and the email created, it’s time to actually send the email, which is done using the send()
method of the Swift_Mailer
class.
如您所见, Swift_MailTransport
用于创建传输层的实例,该实例将使用本机PHP mail()
函数。 然后,我创建了一个Swift_Message
实例,您可以将其视为电子邮件对象。 在以下几行中,我使用setTo()
方法设置收件人,使用setSubject()
设置电子邮件主题,使用setBody()
设置电子邮件正文,并使用setFrom()
方法设置发件人。 定义了层并创建了电子邮件之后,就可以实际发送电子邮件了,这是使用Swift_Mailer
类的send()
方法完成的。
There is no doubt that attachments are a staple of today’s email systems. No one can live without them. This slightly more complicated example will show you how to send an email that not only has an attachment but also other features.
毫无疑问,附件是当今电子邮件系统的主要组成部分。 没有他们,谁也活不下去。 这个稍微复杂一点的示例将向您展示如何发送不仅具有附件而且具有其他功能的电子邮件。
Two additional receivers, one in CC and the second in BCC using setCc()
and setBcc()
.
另外两个接收器,一个在CC中,另一个在BCC中,使用setCc()
和setBcc()
。
One attachment retrieved from disk using the attach()
method.
使用attach()
方法从磁盘检索到一个附件。
A custom SMTP configuration using the Swift_SmtpTransport
class.
使用Swift_SmtpTransport
类的自定义SMTP配置。
Know what recipients have not received the email using the second parameter of the send()
method.
使用send()
方法的第二个参数知道哪些收件人没有收到电子邮件。
<?php
require_once 'lib/swift_required.php';
// Create the SMTP configuration
$transport = Swift_SmtpTransport::newInstance("smtp.fake.com", 25);
$transport->setUsername("Username");
$transport->setPassword("Password");
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
"hello@gmail.com" => "Aurelio De Rosa",
"test@fake.com" => "Audero"
));
$message->setCc(array("another@fake.com" => "Aurelio De Rosa"));
$message->setBcc(array("boss@bank.com" => "Bank Boss"));
$message->setSubject("This email is sent using Swift Mailer");
$message->setBody("You're our best client ever.");
$message->setFrom("account@bank.com", "Your bank");
$message->attach(Swift_Attachment::fromPath("path/to/file/file.zip"));
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message, $failedRecipients);
// Show failed recipients
print_r($failedRecipients);
I used a different transport layer, an SMTP one that is set using the Swift_SmtpTransport
class. It accepts two parameters: the SMTP server and the connection port. You use the instance to set an appropriate username and password to access the server using the setUsername()
and setPassword()
methods. Then, just like the first example, I created an Swift_Message
object and set the recipients, the subject, and so on. However, this time I also took advantage of the setCc()
and the setBcc()
methods that, as you might guess, allow you to set carbon copy and blind carbon copy recipients.
我使用了另一个传输层,即使用Swift_SmtpTransport
类设置的SMTP传输层。 它接受两个参数: SMTP服务器和连接端口。 您可以使用实例设置适当的用户名和密码,以使用setUsername()
和setPassword()
方法访问服务器。 然后,就像第一个示例一样,我创建了一个Swift_Message
对象并设置了收件人,主题等。 但是,这一次,我也利用了setCc()
和setBcc()
方法,您可能会猜到它们允许您设置抄送副本和盲抄收件人。
The key method of this example is attach()
which attaches a file taken from the hard disk using the static method fromPath()
that takes the path to the file you want to attach as its parameter. Note that this time I also print the number of failed recipients retrieved using the send()
method’s second parameter.
此示例的关键方法是attach()
,它使用静态方法fromPath()
附加从硬盘上获取的文件,该方法将要附加的文件的路径作为其参数。 请注意,这次我还将打印使用send()
方法的第二个参数检索的失败收件人的数量。
The third and final example shows you how to use the Decorator plugin, ideal for things like sending newsletters to your subscribers. It allows you to send the same email to several recipients having small differences such as the recipient name inside the email body. The plugin will look inside the template (the body) and will replace the placeholders with the set values.
第三个也是最后一个示例向您展示了如何使用Decorator插件,该插件非常适合向订阅者发送新闻通讯之类的事情。 它使您可以将相同的电子邮件发送给差异很小的多个收件人,例如电子邮件正文中的收件人名称。 插件将在模板(主体)内部查看,并将占位符替换为设置值。
To use the plugin, you first need to register it using the registerPlugin()
method and then build and use an array of replacement values. In the following code I’ll put two placeholders, username and transactions, which will be programmatically replaced by values referring to the user’s email.
要使用该插件,您首先需要使用registerPlugin()
方法进行registerPlugin()
,然后构建并使用一组替换值。 在下面的代码中,我将放置两个占位符, 用户名和交易 ,将以编程方式替换为引用用户电子邮件的值。
<?php
require_once 'lib/swift_required.php';
// Usually you want to replace the following static array
// with a dynamic one built retrieving users from the database
$users = array(
array(
"fullname" => "Aurelio De Rosa",
"operations" => 100,
"email" => "hello@gmail.com"
),
array(
"fullname" => "Audero",
"operations" => 50,
"email" => "test@fake.com"
)
);
// Create the replacements array
$replacements = array();
foreach ($users as $user) {
$replacements[$user["email"]] = array (
"{fullname}" => $user["fullname"],
"{transactions}" => $user["operations"]
);
}
// Create the mail transport configuration
$transport = Swift_MailTransport::newInstance();
// Create an instance of the plugin and register it
$plugin = new Swift_Plugins_DecoratorPlugin($replacements);
$mailer = Swift_Mailer::newInstance($transport);
$mailer->registerPlugin($plugin);
// Create the message
$message = Swift_Message::newInstance();
$message->setSubject("This email is sent using Swift Mailer");
$message->setBody("You {fullname}, are our best client ever thanks " .
" to the {transactions} transactions you made with us.");
$message->setFrom("account@bank.com", "Your bank");
// Send the email
foreach($users as $user) {
$message->setTo($user["email"], $user["fullname"]);
$mailer->send($message);
}
The Decorator plugin constructor accepts one parameter: an array of values to replace the placeholders. Each value of this array uses the user’s email for its key and a sub-array that contains placeholder-replacement pairs. This is exactly the aim of the $replacements
array. In the example above, as placeholders I used a string inside two brackets (i.e. {fullname}
) but you can use whatever you want. This time, I haven’t set all the recipients in the same statement as before and I used a for
loop. This is done because the plugin intercepts the sending process, reads the recipient email, and replaces the placeholders using the values of the replacement array.
Decorator插件构造函数接受一个参数:一组用于替换占位符的值。 该数组的每个值都将用户的电子邮件用作其键以及包含占位符-替换对的子数组。 这正是$replacements
数组的目标。 在上面的示例中,作为占位符,我在两个方括号内使用了一个字符串(即{fullname}
),但是您可以使用任何所需的字符串。 这次,我没有像以前一样在所有语句中设置所有收件人,而是使用了for
循环。 这样做是因为插件拦截了发送过程,读取了收件人电子邮件,并使用替换数组的值替换了占位符。
In this article I showed how you can easily send emails using Swift Mailer. This is a very powerful library that, as you’ve seen, allows you to do a lot of things using an OOP approach. Of course Swift Mailer has a lot of other methods and classes I’ve not covered in this article. You can study up on them in the official documentation, but this should be enough to get you started sending emails without hassle.
在本文中,我展示了如何使用Swift Mailer轻松发送电子邮件。 如您所见,这是一个非常强大的库,它使您可以使用OOP方法执行很多操作。 当然,Swift Mailer还有很多其他方法和类,我在本文中没有涉及。 您可以在官方文档中对其进行研究,但这足以使您轻松发送电子邮件。
Image via Fotolia
图片来自Fotolia
翻译自: https://www.sitepoint.com/sending-email-with-swift-mailer/
mailer deamon