How to Send Emails Using Swift Mailer

Swift Mailer integrates into any web app written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features. Swift Mailer supports SMTP authentication, HTML emails and attachments, bulk emails, and requests for read reciepts and greeting messages. It’s easy to integrate and use.


Swift Mailer offers:

  • Send emails using SMTP, sendmail, postfix or a custom Transport implementation of your own
  • Support servers that require username & password and/or encryption
  • Protect from header injection attacks without stripping request data content
  • Send MIME compliant HTML/multipart emails
  • Use event-driven plugins to customize the library
  • Handle large attachments and inline/embedded images with low memory use

Click here to a list of SMTP and POP3 Server.


Download SwiftMailer zip file, here’s site link:


Unzip this archive, find a file name called: swift_required.php, it should be available at this location: swift\lib\. In addition, I will require swift_required.php. After integrated Swift Mailer, you need to load it in your file.


Initialize Swift Mailer

First, I will initialize Swift Mailer by requiring the swift_required.php file, then create the swift mailer class. Swift_SmtpTransport is used to create a transport instance. Swift_Message is the object of email, setTo() method holds the recipient email address, setSubject holds the subject of the email, setBody() contains the whole message of the email, and lastly, setFrom() contains the sender email. In the next line, I set a condition to check whether the target path is empty and then attach the files to the email. Last line, the email will be sent by the send() method. Click here to a list of SMTP and POP3 Server.


Please note that I have set up an optional argument $targetpath = null because even if you do not attach files to an email, you will still be able to send it. Finally, I will pass all the values to sendMail() function to send the email.

Note: For sending emails from Gmail SMTP, you need to Turn On the access of less secure apps from account settings. Next, go to this URL and allow Google to access your application.



In this article, I introduced Swift Mailer and created a simple class and methods to send an email. You could easily implement advanced features and automate the process of sending system generated emails. Swiftmailer is a secure email library. I personally recommend that you send emails using Swift Mailer in all your future PHP projects.

If you have a question or would like to contribute to the discussion, do leave a comment below!

Prakash S

Prakash S

I would like to introduce myself as a Software professional opting for the career in software industry. I'm Prakash S, a MCA graduate and trained as industry level practice for Software technology. Basically I am a PHP Developer but now days exploring more in HTML5, CSS, AngularJS and jQuery libraries.