If you want to send emails in Python, use a reliable and secure email API solution. In this article, you’ll learn the step-by-step process of sending emails in Python using the API method.
To streamline email sending in Python, you can use a transactional email service such as Mailtrap, Gmail API, Sendgrid, etc. And, an API also allows you to automate much of email sending
Now, I’ll show you how to send different types of emails (plain text, email with attachments, HTML emails) and email multiple recipients in Python using an email API Before that, let’s understand how to set up an email API:
This ensures recipients only receive genuine emails, avoiding spam. Based on the service provider, complete domain authentication.
pip install myemailapi
Step 1: Create your mail object and fill in the variables
1 |
import myemailapi |
2 |
|
3 |
# Create a mail object
|
4 |
|
5 |
mailobj = Mail( |
6 |
newsender= Address(email1=“testmail@domain.com”, name=“Test Sender”), |
7 |
to=[Address(email1=“reciever@example.com”, name=“Test Receiver”)], |
8 |
newsubject=“Test email”, |
9 |
newtext=“This is a plain-text email.”, |
10 |
)
|
Now, create the email client using your API tokens by:
Step 2: Send your message
# Define email API client and send email
1 |
emailclient = MyEmailAPIClient(newtoken=“new-api-key”) |
2 |
emailclient.send(mailobj) |
Here’s the complete code snippet:
1 |
from myemailapi import Mail, EAddress, MyEmailAPIClient |
2 |
mailobj = Mail( |
3 |
# Define sender address and name
|
4 |
newsender=Address(email1=“testmail@domain.com”, name=“Test Sender”), |
5 |
# Define receivers
|
6 |
to=[Address(email1=“receiver@example.com”, name=“Test Receiver”)], |
7 |
# Email subject
|
8 |
newsubject=“Test email”, |
9 |
# Define plain text
|
10 |
newtext=“Hi,/nThis is a plain-text email.”, |
11 |
)
|
12 |
|
13 |
# Define MyEmailAPIClient using your API keys
|
14 |
emailclient = MyEmailAPIClient(newtoken=“new-api-key”) |
15 |
|
16 |
# Send your plain-text email
|
17 |
emailclient.send(mailobj) |
18 |
|
19 |
print(“Congrats! You’ve successfully sent your first plain text email in Python.”) |
Follow the instructions to send an HTML email:
Here’s the full code snippet for sending a Python email with HTML content:
1 |
from myemailapi import Mail, EAddress, MyEmailAPIClient |
2 |
|
3 |
mailobj = Mail( # Create the Mail object for the HTML email |
4 |
# Define sender address and name
|
5 |
newsender=Address(emailaddress=“testmail@domain.com”, name=“Test Sender”), |
6 |
# Define receivers
|
7 |
to=[Address(emailaddress=“receiver@example.com”, name=“Test Receiver”)], |
8 |
# Define email subject
|
9 |
newsubject=“HTML email”, |
10 |
# Define text
|
11 |
newtext=“Hi,/nEmail client can’t render HTML? Use this fallback text.”, |
12 |
html_text=“”” |
13 |
<html> |
14 |
<head> |
15 |
<title>Titletitle> |
16 |
head> |
17 |
|
18 |
<body> |
19 |
<h1>Hi, there!h1> |
20 |
<p>This is text HTML content sent using MyEmailAPI.p> |
21 |
body> |
22 |
html> |
23 |
“””, |
24 |
)
|
25 |
|
26 |
# Define MyEmailAPIClient using your API keys
|
27 |
emailclient = MyEmailAPIClient(newtoken=“new-api-key”) |
28 |
|
29 |
# Send your HTML email
|
30 |
emailclient.send(mailobj) |
31 |
|
32 |
print(“Congrats! You’ve successfully sent your first HTML email.”) |
Follow the below instructions:
Here’s the complete code for sending an email to multiple recipients in Python:
1 |
from myemailapi import Mail, EAddress, MyEmailAPIClient |
2 |
|
3 |
# Create the Mail object for multiple recipients
|
4 |
mailobj = Mail( |
5 |
# Define sender address and name
|
6 |
newsender=Address(emailaddress=“testmail@domain.com”, name=“Test Sender”), |
7 |
# Define receivers
|
8 |
to=[ |
9 |
Address(emailaddress=“receiver1@example.com”, name=“Test Receiver 1”)], |
10 |
Address(emailaddress=“receiver2@example.com”, name=“Test Receiver 2”)], |
11 |
],
|
12 |
# Define email subject
|
13 |
newsubject=“ This is email subject”, |
14 |
# Define text
|
15 |
newtext=“Hello, /nThis email has multiple recipients.”, |
16 |
)
|
17 |
|
18 |
# Define MyEmailAPIClient using your API keys
|
19 |
emailclient = MyEmailAPIClient(newtoken=“new-api-key”) |
20 |
|
21 |
# Send email
|
22 |
emailclient.send(mailobj) |
23 |
|
24 |
print(“Congrats! You’ve successfully sent emails to multiple recipients in Python.”) |
Follow the below instructions:
base64.b64encode
Here’s the complete code:
1 |
from myemailapi import Mail, EAddress, MyEmailAPIClient Attachment, Disposition |
2 |
import base64 |
3 |
from pathlib import Path |
4 |
|
5 |
# Define files to attach
|
6 |
filepath = Path(“thisis/your/filepath/abc.pdf”) # Insert your file’s name |
7 |
filecontent = filepath.read_bytes() |
8 |
|
9 |
# Base64 is used to encode the content of the file
|
10 |
encodedcontent = base64.b64encode(filecontent) |
11 |
|
12 |
# Specify the email object with an attachment
|
13 |
mailobj = Mail( |
14 |
# Define sender address and name
|
15 |
newsender=Address(emailaddress=“testmail@domain.com”, name=“Test Sender”), |
16 |
# Define receiver
|
17 |
to=[Address(emailaddress=“receiver@example.com”, name=“Test Receiver”)], |
18 |
# Define email subject
|
19 |
newsubject=“ Attachment inside!”, |
20 |
# Define text
|
21 |
newtext=“Hello, /nThis email has an important attachment.”, |
22 |
# Define email attachment
|
23 |
attachments_new=[ |
24 |
Attachment( |
25 |
content_new=encodedcontent, |
26 |
filename_new=filepath.name, # The file name |
27 |
disposition_new=Disposition.ATTACHMENT, |
28 |
mimetype_new= “application/pdf”, # The file type used here is PDF |
29 |
)
|
30 |
],
|
31 |
)
|
32 |
|
33 |
# Define MyEmailAPIClient using your API keys
|
34 |
emailclient = MyEmailAPIClient(newtoken=“new-api-key”) |
35 |
|
36 |
# Send email
|
37 |
emailclient.send(mailobj) |
38 |
|
39 |
print(“Congrats! You’ve successfully sent emails with an attachment.”) |
Before you send bulk emails using an email API service, make sure you test it beforehand on a test server. This is similar to testing a new application or rolling out a new feature in your app.
An email testing API will work like a third-party web server. You’ll get a secure staging environment where you can handle your email traffic internally and check if the email sending functionality is working fine. You can also detect and resolve bugs and errors before sending your emails to targeted recipients. In addition, you can preview and evaluate your email content across different devices and email clients in order to optimize your message.
As a result, you’ll be able to:
Thus, before you send your emails, send them to a designated email address using an email testing API. View the email content, check links, fix issues, and then only send your emails to the target audience.
In the below section, I’ll show you how to test an email using a hypothetical email testing API – ‘EtestAPI’. Here’s how to get started step-by-step:
Here’s the full code to test your email using EtestAPI:
1 |
# Import ‘json’ and ‘requests’ libraries for handling JSON data and HTTP requests
|
2 |
import requests |
3 |
import json |
4 |
|
5 |
# Define a function ‘test_my_email’ with parameters for email testing
|
6 |
def test_my_email(etestapi_token1, inbox_id1, sender_email1, recipient_email1, subject, text): |
7 |
url = f"https://api.etestapi.com/v1/inboxes/{inbox_id1}/messages" |
8 |
headers = { |
9 |
"Authorization": f"Bearer {etestapi_token1}", |
10 |
"Content-Type": "application/json", |
11 |
}
|
12 |
|
13 |
data = { |
14 |
"from": [{“sender_email1”: “sender@domain.com”, “name”: “Test Sender”}], |
15 |
"to": [{“recipient_email1”: “receiver@example.com”, “name”: “Test Receiver”}], |
16 |
"subject": “Email Test”, |
17 |
"text": “Hi,/nLet’s perform email testing”, |
18 |
}
|
19 |
|
20 |
|
21 |
# Convert data to a JSON string
|
22 |
json_data = json.dumps(data) |
23 |
|
24 |
# make a POST request using ‘requests.post’ to send your email to EtestAPI and get the response in JSON
|
25 |
response = requests.post(url, headers=headers, json_data) |
26 |
|
27 |
if response.status_code == 200: |
28 |
print("Congrats! Your email test is successful!") |
29 |
print("The test email is sent to EtestAPI inbox.") |
30 |
else: |
31 |
print(f"Test email failed: {response.status_code}") |
32 |
print(response.text) |
Explanation:
Using a reliable and secure email API solution allows you to send emails faster, without hassles. If you run a business, an email API will help you automate the process. Thus, you can send highly personalized and bulk emails quickly with a few lines of code as we’ve mentioned above.
We also recommend you refer to the Python documentation and the email API solution you prefer. Keep experimenting with new code and exploring email-sending functionalities.