Sending Emails with Swift Mailer

This post shares insights on creating and sending emails using Swift Mailer. To know more about the topic, feel free to check Send Emails with Swift Mailer from PHP Apps

Swift Mailer is easy to use with any PHP framework. To send messages, you can integrate Swift Mailer into popular sending providers like Sendgrid and similar as well as external SMTP servers.

Swift Mailer is used as the main mail option in frameworks like Yii2 and CMS like Drupal, Laravael’s email API is built on top of the Swift Mailer library as well.

To install Swift Mailer, we need to use Composer:

$ composer require "swiftmailer/swiftmailer:^6.0

Correspondingly, to create transport, we need hostname, port, username, and password

Making an email

In Swift Mailer, messages are composed with the help of Swift_Message class.

Let’s start by creating a message from top to bottom, likely to an email client: set recipient, sender, and a subject. Usually, we will make it with setSubject(), setTo(), and setFrom() methods.

To include several recipients, use an array and to add recipients in copy, use setCc() or setBcc(). You can set name headers with associative arrays. Also, you can embed images and attachments into our email, which is explained in the guide.

For more details and alternatives, refer to the corresponding section in the Swift Mailer documentation.

Sending an email

Before sending, you have to ensure that all the required transport data is set. For example, if you are going to test emails prior to sending, you should use the Mailer class to send the message with all the credentials of your testing tool. In our case, it is Mailtrap.

$mailer->send($message);

This message can be send with Swift Mailer:
This is image title

Code:

 try {
$transport = (new Swift_SmtpTransport('smtp.mailtrap.io', 2525))
        ->setUsername('1a2b3c4d5e6f7g')
        ->setPassword('1a2b3c4d5e6f7g');
    $mailer = new Swift_Mailer($transport);
public function index($name, \Swift_Mailer $mailer)
{
 $message = (new Swift_Message())
 ->setSubject('Here should be a subject')
->setFrom(['support@example.com'])
 ->setTo(['newuser@example.com' => 'New Mailtrap user'])
->setCc([
'product@example.com' => 'Product manager'
]);
$message->setBody(
'<html>' .
' <body>' .
'  <img src="' .
     $message->embed(Swift_Image::fromPath('image.png')) .
   '" alt="Image" />' .
'  <p>Welcome to Mailtrap!</p>’.
‘Now your test emails will be <i>safe</i>’ .
' </body>' .
'</html>',
  'text/html'
);
$message->addPart('Welcome to Mailtrap, now your test emails will be safe', 'text/plain');
$message->attach(Swift_Attachment::fromPath('/path/to/confirmation.pdf'));
$mailer->send($message);

#symfony #php

Sending Emails with Swift Mailer
2.75 GEEK