Sending Emails with MailerSend and Python

Prerequisites

Before we begin, you will need to have the following:

  • A MailerSend account
  • A MailerSend API key
  • Python installed on your local machine

Install MailerSend SDK

First, you need to install the MailerSend SDK for Python. You can do this using pip, the package installer for Python, by running the following command in your terminal:

pip install mailersend

Import MailerSend Library

Once you have installed the MailerSend SDK, you can create a new Python file in your project directory. Import the MailerSend library by adding the following code at the top of your file:

from mailersend import emails

Create a MailerSend Client

Next, create a new MailerSend client object by passing your API key to the constructor:

mailer = emails.NewEmail(os.getenv('YOUR_API_KEY'))

Replace YOUR_API_KEY with your actual MailerSend API key.

Send an Email

To send an email, you will need to provide the recipient's email address, subject, and message body. Here's an example code that sends an email using MailerSend:

from mailersend import emails

mailer = emails.NewEmail('YOUR_API_KEY')

mail_body = {}

mail_from = {
    "name": "Sender Name",
    "email": "from@example.com",
}

recipients = [
    {
        "name": "Recipient Name",
        "email": "recipient@example.com",
    }
]

reply_to = [
    {
        "name": "Reply Name",
        "email": "reply@example.com",
    }
]

mailer.set_mail_from(mail_from, mail_body)
mailer.set_mail_to(recipients, mail_body)
mailer.set_subject("Hello!", mail_body)
mailer.set_html_content("Hello, this is an example email from MailerSend", mail_body)
mailer.set_plaintext_content("Hello, this is an example email from MailerSend", mail_body)
mailer.set_reply_to(reply_to, mail_body)

mailer.send(mail_body)

Replace YOUR_API_KEY, **from@example.com**, recipient@example.com, **reply@example.com**, Recipient Name, Example email, and Hello, this is an example email from MailerSend! with your own values.

Congratulations, you have successfully sent an email using Python and MailerSend SDK!

What’s next?

Last Updated: