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.
You can install Swiftmailer through Composer by executing the following command.
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
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
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.
You can create a new message by creating a new instance of
Swift_Message class. From there, call the
setTo methods to add the details of the email.
1 2 3 4 5
Optionally, you can set an alternative body:
You can also attach a file:
If you want to send to multiple clients, then you can pass in additional items to the
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
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.
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.