DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • A Developer’s Guide to Multithreading and Swift Concurrency
  • Automate Developer Routine With Swift in iOS Development
  • How to Make a Picture-in-Picture Feature in iOS App Using AVFoundation
  • Why You Might Need To Know Algorithms as a Mobile Developer: Emoji Example

Trending

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Merge HTML Documents in Java
  • What’s Got Me Interested in OpenTelemetry—And Pursuing Certification
  • Monoliths, REST, and Spring Boot Sidecars: A Real Modernization Playbook
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Use Swift Mailer for Sending Emails

How to Use Swift Mailer for Sending Emails

Swift Mailer is easy to use with any PHP framework. Swift Mailer is compatible with many SMTP servers. It is utilized to create and send emails from the apps.

By 
Dmytro Zaichenko user avatar
Dmytro Zaichenko
·
Jun. 22, 20 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
4.9K Views

Join the DZone community and get the full member experience.

Join For Free

About Swift Mailer 

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. In the case of using Mailtrap, it will look like this:

PHP
 




xxxxxxxxxx
1



1
$transport = (new Swift_SmtpTransport('smtp.mailtrap.io', 2525))
2
  ->setUsername('1a2b3c4d5e6f7g') // generated by Mailtrap
3
  ->setPassword('1a2b3c4d5e6f7g') // generated by Mailtrap
4
;
5
$mailer = new Swift_Mailer($transport);


How to Create 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(). Also, you can set name headers with associative arrays:

PHP
 




xxxxxxxxxx
1
14



1
// Create the message
2
$message = (new Swift_Message())
3
  // Add subject
4
  ->setSubject('Here should be a subject')
5
 
          
6
  //Put the From address 
7
->setFrom(['support@example.com'])
8
 
          
9
  // Include several To addresses
10
 ->setTo(['newuser@example.com' => 'New Mailtrap user'])
11
->setCc([
12
'support@example.com',
13
‘product@example.com’ => ‘Product manager’
14
]);


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

Adding Content

Also, we can add different types of HTML content into our messages.

In Swift Mailer, you need to define which type of content you are going to add to your message body. It can be text/html, text/plain, or both.

Wherever possible, include a plain text version for the HTML content. If for some reason the HTML part won’t be rendered, your recipient will still be able to understand the content of your message.

For this purpose, use setBody() method and addPart() for the alternative. For example:

PHP
 




x



1
$message->setBody(<p>'Welcome to Maitrap!</p>
2
Now your test emails will be <i>safe</i>', 'text/html');
3
$message->addPart('Welcome to Mailtrap, now your test emails will be safe', 'text/plain');



Embedding Images

Swift Mailer lets you embed your image directly, without any additional manipulations. Use Swift_EmbeddedFile::fromPath(). method for this purpose. It is very similar to inserting an image to the body of your message in many email clients.

So, you should have an image file saved locally on your computer or you can even add an image hosted on some website. For the latter, allow_url_fopen should be enabled in your PHP installation (read more about it in the PHP manual).

From your computer:

PHP
 




xxxxxxxxxx
1
15



1
// Create the message, you can add the subject right here if you like
2
$message = new Swift_Message('The subject should be here');
3
 
          
4
// Set the body
5
$message->setBody(
6
'<html>' .
7
' <body>' .
8
'Here is our new logo <img data-fr-src="’ . 
9
     $message->embed(Swift_Image::fromPath('newlogo.png')) .
10
   ‘" alt="new logo" />' .
11
' Let us know how you like it'.
12
' </body>' .
13
'</html>',
14
  'text/html' // don’t forget to mark the content type
15
);



From URL:

PHP
 




xxxxxxxxxx
1
11



1
$message->setBody(
2
'<html>' .
3
' <body>' .
4
'  Here is our new logo <img data-fr-src="' .
5
     $message->embed(Swift_Image::fromPath('https://mailtrap.io/newlogo.png')) .
6
   '" alt="Image" />' .
7
'  Let us know how you like it' .
8
' </body>' .
9
'</html>',
10
  'text/html'
11
);


Including Attachments

You can attach files saved locally, from URLs, or add dynamic content. The difference is that you use Swift_Attachment class here and Swift_Message's attach() method.

PHP
 




xxxxxxxxxx
1
13



1
// For the regular file types like docs, spreadsheets, or images, you can go without the content type 
2
$message->attach(Swift_Attachment::fromPath('/path/to/image.jpg'));
3
 
          
4
// attach a file from a URL 
5
$message->attach(Swift_Attachment::fromPath('https://mailtrap.io/newlogo.jpg'));
6
// Create the attachment and rename it
7
$message->attach(
8
  Swift_Attachment::fromPath('/path/to/newlogo.jpg')->setFilename('logofinal.jpg')
9
);
10
// now let’s add a pdf file created via GD and set its content type
11
$data = create_confirmation_pdf_data();
12
$attachment = new Swift_Attachment($data, 'confirmation.pdf', 'application/pdf');
13
$message->attach($attachment);



How to Send 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);

As an illustration, this is a code for an email with HTML/plain text, image, and attachment:

PHP
 




xxxxxxxxxx
1
10



1
require_once 'path/to/vendor/autoload.php';
2
3
{try
4
5
$transport = (new Swift_SmtpTransport('smtp.mailtrap.io', 2525))
6
        ->setUsername('1a2b3c4d5e6f7g')
7
        ->setPassword('1a2b3c4d5e6f7g');
8
    $mailer = new Swift_Mailer($transport);
9
public function index($name, \Swift_Mailer $mailer)
10
11
{
12
 $message = (new Swift_Message())
13
 ->setSubject('Here should be a subject')
14
->setFrom(['support@example.com'])
15
 ->setTo(['newuser@example.com' => 'New Mailtrap user'])
16
->setCc([
17
'product@example.com' => 'Product manager'
18
]);
19
$message->setBody(
20
'<html>' .
21
' <body>' .
22
'  <img data-fr-src="' .
23
     $message->embed(Swift_Image::fromPath('image.png')) .
24
   '" alt="Image" />' .
25
'  <p>Welcome to Mailtrap!</p>’.
26
‘Now your test emails will be <i>safe</i>’ .
27
' </body>' .
28
'</html>',
29
  'text/html'
30
);
31
$message->addPart('Welcome to Mailtrap, now your test emails will be safe', 'text/plain');
32
$message->attach(Swift_Attachment::fromPath('/path/to/confirmation.pdf'));
33
$mailer->send($message);



If we did everything right, the message will look like this:

example of finished swift mailer


Swift Mailer and SMTP Server

To use Swift Mailer with an external SMTP server does not require much effort. The only critical point to remember is to set the correct transport (as we did with Mailtrap in the example above).

Swift Mailer is one of the most popular PHP libraries so it will be easy to find examples of integration with various services. However, to ensure effective integration, it's better to review the documentation of your provider.

Swift (programming language)

Published at DZone with permission of Dmytro Zaichenko. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Developer’s Guide to Multithreading and Swift Concurrency
  • Automate Developer Routine With Swift in iOS Development
  • How to Make a Picture-in-Picture Feature in iOS App Using AVFoundation
  • Why You Might Need To Know Algorithms as a Mobile Developer: Emoji Example

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!