Wern Ancheta

Adventures in Web Development.

Getting Started With Swiftmailer

| Comments

In this tutorial I’m going to walk you through how to use Swift Mailer in your PHP applications. Swift Mailer, as the name suggests is a library for sending emails in PHP.

Installation

You can install Swiftmailer through Composer by executing the following command.

1
composer require swiftmailer/swiftmailer

Usage

To start sending emails you first have to create a new instance of the Swift_SmtpTransport class. This accepts the host as its first argument and the port as its second. You can then set your username and password by calling the setUsername and setPassword methods. So for example, you want to use your mandrill for sending emails, you can use the following. Just replace the username and password to that of your mandrill account.

1
2
3
$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587)
  ->setUsername('your-mandrill-username')
  ->setPassword('your-mandrill-password');

Next, create a new Swift mailer instance and passing in the transport object as the argument. You can use this later on to send messages.

1
$mailer = Swift_Mailer::newInstance($transport);

You can create a new message by creating a new instance of Swift_Message class. From there, call the setSubject, setBody, setFrom and setTo methods to add the details of the email.

1
2
3
4
5
$message = Swift_Message::newInstance()
  ->setSubject('YOUR-SUBJECT')
  ->setBody('BODY-OF-YOUR-MESSAGE')
  ->setFrom(array('YOUR-EMAIL@HOST.COM' => 'YOUR-USER-NAME'))
  ->setTo(array('EMAIL-TO@HOST.COM' => 'NAME-TO@HOST.COM'));

Optionally, you can set an alternative body:

1
$message->addPart('YOUR-ALTERNATIVE-BODY', 'text/html');

You can also attach a file:

1
$message->attach(Swift_Attachment::fromPath('/path/to/file.pdf'));

If you want to send to multiple clients, then you can pass in additional items to the setTo method:

1
$message->setTo(array('EMAIL-TO@HOST.COM' => 'NAME-TO@HOST.COM', 'ANOTHER-EMAIL@HOST.COM' => 'ANOTHER-NAME@HOST.COM'));

Finally, you can send the message by calling the send method in the mailer instance that you have created earlier. Pass in the message as its argument.

1
2
3
4
5
6
try {
    $response = $mailer->send($message);
}catch (Exception $e){
    echo 'error occured while trying to send your message';
    echo $e->getMessage();
}

The send method will return 1 as its response if the message was sent successfully. If not then it will return an error, that’s why you need to wrap it in a try catch block.

If you’re using Laravel, SwiftMailer is already added as a dependency by default. All you have to do is update the mail configuration file. If you’re using another framework, you can just follow the examples here.

Conclusion

That’s it! In this tutorial you’ve learned how to use SwiftMailer on your php applications. If you want to learn more, be sure to check out the official docs.

Comments