亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Key Takeaways
The Swift Mailer Family of Classes
A Basic Example
An Example with Attachments
Using a Template
Conclusion
Frequently Asked Questions about Swift Mailer
How can I install Swift Mailer using Composer?
How can I send an email with Swift Mailer?
How can I add attachments to an email with Swift Mailer?
How can I send HTML emails with Swift Mailer?
How can I handle errors in Swift Mailer?
How can I use Swift Mailer with Gmail?
How can I send multiple emails with Swift Mailer?
How can I use Swift Mailer with Symfony?
How can I set the priority of an email with Swift Mailer?
How can I send emails asynchronously with Swift Mailer?
Home Backend Development PHP Tutorial PHP Master | Sending Email with Swift Mailer

PHP Master | Sending Email with Swift Mailer

Feb 25, 2025 pm 02:16 PM

PHP Master | Sending Email with Swift Mailer

PHP Master | Sending Email with Swift Mailer

Key Takeaways

  • Swift Mailer is a powerful, component-based library that allows programmers to send emails easily using an object-oriented approach, with minimal requirements of PHP 5.2 or higher with the SPL extension and a minimum memory limit of 8MB.
  • Swift Mailer can be installed through PEAR or by uploading the files using an FTP. It consists of more than 150 classes and interfaces, including the Mailer, Transporters, MIME Entities, Encoders, and Plugins.
  • Swift Mailer provides functionalities to create an email with multiple recipients, a subject, and a plain-text body. It also allows for attachments, custom SMTP configuration, and tracking recipients who do not receive the email.
  • Swift Mailer also has a Decorator plugin that allows you to send the same email to several recipients with small differences, such as the recipient name inside the email body. This is beneficial for tasks like sending newsletters to subscribers.
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. 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. 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. Installing from the PEAR channel is just a matter of type two commands:
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.

The Swift Mailer Family of Classes

Swift Mailer is made of more than 150 classes and interfaces grouped together in several components. Each of them have a specific purpose.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.

A Basic Example

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. 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.
pear channel-discover pear.swiftmailer.org
pear install swift/swift
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.

An Example with Attachments

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().
  • One attachment retrieved from disk using the attach() method.
  • A custom SMTP configuration using the Swift_SmtpTransport class.
  • Know what recipients have not received the email using the second parameter of the send() method.
pear channel-discover pear.swiftmailer.org
pear install swift/swift
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. 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.

Using a Template

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. 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.
<span><span><?php
</span></span><span><span>require_once 'lib/swift_required.php';
</span></span><span>
</span><span><span>// Create the mail transport configuration
</span></span><span><span>$transport = Swift_MailTransport<span>::</span>newInstance();
</span></span><span>
</span><span><span>// Create the message
</span></span><span><span>$message = Swift_Message<span>::</span>newInstance();
</span></span><span><span>$message->setTo(array(
</span></span><span>  <span>"hello@gmail.com" => "Aurelio De Rosa",
</span></span><span>  <span>"test@fake.com" => "Audero"
</span></span><span><span>));
</span></span><span><span>$message->setSubject("This email is sent using Swift Mailer");
</span></span><span><span>$message->setBody("You're our best client ever.");
</span></span><span><span>$message->setFrom("account@bank.com", "Your bank");
</span></span><span>
</span><span><span>// Send the email
</span></span><span><span>$mailer = Swift_Mailer<span>::</span>newInstance($transport);
</span></span><span><span>$mailer->send($message);</span></span>
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.

Conclusion

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. Image via Fotolia

Frequently Asked Questions about Swift Mailer

How can I install Swift Mailer using Composer?

Swift Mailer can be easily installed using Composer, a tool for dependency management in PHP. To install Swift Mailer, you need to have Composer installed on your system. Once you have Composer installed, you can install Swift Mailer by running the following command in your project directory: composer require "swiftmailer/swiftmailer:^6.0". This command tells Composer to download the Swift Mailer package and its dependencies into your project.

How can I send an email with Swift Mailer?

Sending an email with Swift Mailer involves creating a message, configuring the mailer, and sending the message. Here is a basic example of how to send an email with Swift Mailer:

require_once '/path/to/vendor/autoload.php';

$message = (new Swift_Message())
->setSubject('Hello')
->setFrom(['john@doe.com' => 'John Doe'])
->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])
->setBody('Here is the message itself');

$transport = (new Swift_SmtpTransport('smtp.example.org', 25))
->setUsername('your username')
->setPassword('your password');

$mailer = new Swift_Mailer($transport);

$result = $mailer->send($message);

How can I add attachments to an email with Swift Mailer?

Swift Mailer allows you to add attachments to your emails. You can attach files from a path, a string, or an existing Swift Attachment instance. Here is an example of how to attach a file from a path:

$message = (new Swift_Message())
->setSubject('Hello')
->setFrom(['john@doe.com' => 'John Doe'])
->setTo(['receiver@domain.org'])
->setBody('Here is the message itself')
->attach(Swift_Attachment::fromPath('path/to/image.jpg'));

How can I send HTML emails with Swift Mailer?

Swift Mailer allows you to send HTML emails by setting the body of the message to an HTML string and setting the content type to ‘text/html’. Here is an example:

$message = (new Swift_Message())
->setSubject('Hello')
->setFrom(['john@doe.com' => 'John Doe'])
->setTo(['receiver@domain.org'])
->setBody('

Here is the HTML message itself

', 'text/html');

How can I handle errors in Swift Mailer?

Swift Mailer throws exceptions when an error occurs. You can catch these exceptions to handle errors. Here is an example:

try {
$result = $mailer->send($message);
} catch (Swift_TransportException $e) {
echo 'There was an error while sending the email: ' . $e->getMessage();
}

How can I use Swift Mailer with Gmail?

You can use Swift Mailer with Gmail by configuring the SMTP transport with the Gmail SMTP server settings. Here is an example:

$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
->setUsername('your Gmail username')
->setPassword('your Gmail password');

How can I send multiple emails with Swift Mailer?

You can send multiple emails with Swift Mailer by creating multiple message instances and sending them with the same mailer instance. Here is an example:

$message1 = (new Swift_Message())
->setSubject('Hello')
->setFrom(['john@doe.com' => 'John Doe'])
->setTo(['receiver1@domain.org'])
->setBody('Here is the message itself');

$message2 = (new Swift_Message())
->setSubject('Hello')
->setFrom(['john@doe.com' => 'John Doe'])
->setTo(['receiver2@domain.org'])
->setBody('Here is the message itself');

$result1 = $mailer->send($message1);
$result2 = $mailer->send($message2);

How can I use Swift Mailer with Symfony?

Swift Mailer is integrated with Symfony and can be used as a service. You can send emails with Swift Mailer in Symfony by getting the mailer service and using it to send a message. Here is an example:

$message = (new Swift_Message())
->setSubject('Hello')
->setFrom(['john@doe.com' => 'John Doe'])
->setTo(['receiver@domain.org'])
->setBody('Here is the message itself');

$this->get('mailer')->send($message);

How can I set the priority of an email with Swift Mailer?

You can set the priority of an email with Swift Mailer by calling the setPriority method on the message instance. The priority is an integer between 1 (highest) and 5 (lowest). Here is an example:

$message = (new Swift_Message())
->setSubject('Hello')
->setFrom(['john@doe.com' => 'John Doe'])
->setTo(['receiver@domain.org'])
->setBody('Here is the message itself')
->setPriority(1);

How can I send emails asynchronously with Swift Mailer?

Swift Mailer does not support asynchronous email sending out of the box. However, you can achieve this by using a message queue. You can enqueue messages and then send them in a separate process. This allows your application to continue processing other tasks without waiting for the emails to be sent.

The above is the detailed content of PHP Master | Sending Email with Swift Mailer. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

php regex for password strength php regex for password strength Jul 03, 2025 am 10:33 AM

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

How to combine two php arrays unique values? How to combine two php arrays unique values? Jul 02, 2025 pm 05:18 PM

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

How to create an array in php? How to create an array in php? Jul 02, 2025 pm 05:01 PM

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color

See all articles