Sending Emails with MailerSend and PHP
Before we begin, you need to have the following:
- A MailerSend account. If you don't have one, sign up for a free account on the MailerSend website.
- PHP installed on your computer. You can download it from the official PHP website.
- A text editor or an integrated development environment (IDE) to write and edit PHP code.
Set up the MailerSend PHP SDK
Since this library is built atop of PSR-7 and PSR-18, we need to install some implementations of those interfaces. Run this command in your terminal of choice within the project directory:
composer require php-http/guzzle7-adapter nyholm/psr7
Afterwards it’s time to install the SDK which will provide classes and functions that allow you to interact with the MailerSend API. To install the SDK type the following command:
composer require mailersend/mailersend
Set up the MailerSend API Key
To use the MailerSend API, you need to generate an API key in your MailerSend account and use as so:
use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'INSERT_API_KEY_HERE']);
Now that you have your API key, you can use it in your PHP code to authenticate your requests to the MailerSend API.
Set up the email message
Before you can send an email, you need to set up the email message. This includes defining the recipient(s), subject, body, any attachments, and other parameters you can read about in the MailerSend documentation.
Here's an example of how to set up an email message:
use MailerSend\Helpers\Builder\EmailParams; $recipients = [ new Recipient('firstname.lastname@example.org', 'Recipient Name'), ]; $email = (new EmailParams()) ->setFrom('email@example.com') ->setFromName('Sender Name') ->setRecipients($recipients) ->setSubject('Test Email') ->setHtml('<p>Hello world!</p>') ->setText('Hello world!');
In this example, we use the
EmailParams class to define the parameters to send an email: the sender with their email and name, the recipient with their email and name, the email subject, and the body of the email in both HTML and text format.
Send the email
Finally we are ready to send the email! We'll use the
$mailersend instance created before to send the email. Here's an example of how to send the email:
use Mailersend\Mailersend; $mailerSend->email->send($email);
That's it! Following these steps, you can easily send emails using MailerSend and PHP.