Home >Backend Development >PHP Tutorial >PHP Master | Sending Email with Swift Mailer
pear channel-discover pear.swiftmailer.org pear install swift/swiftThe 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.
pear channel-discover pear.swiftmailer.org pear install swift/swiftAs 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.
pear channel-discover pear.swiftmailer.org pear install swift/swiftI 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.
<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.
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.
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);
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'));
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');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();
}
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');
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);
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);
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);
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!