If you wish to ship emails in Python, use a dependable and safe e-mail API resolution. On this article, you’ll be taught the step-by-step technique of sending emails in Python utilizing the API technique.
Organising Electronic mail API
To streamline e-mail sending in Python, you need to use a transactional e-mail service akin to Mailtrap, Gmail API, Sendgrid, and many others. And, an API additionally lets you automate a lot of e-mail sending
Now, I’ll present you easy methods to ship several types of emails (plain textual content, e-mail with attachments, HTML emails) and e-mail a number of recipients in Python utilizing an email API Earlier than that, let’s perceive easy methods to arrange an e-mail API:
- Select an e-mail API: To get began, select an e-mail API based on your preferences. Ensure that it provides Python SDKs to ship automated emails (for instance Mailtrap’s Python SDK).
- Join: Signal as much as the chosen e-mail API supplier.
- Join and confirm your area: Subsequent, join and confirm your area with the e-mail API service supplier you’ve chosen. If not verified, it is possible for you to to ship emails to the account proprietor’s e-mail handle solely.
This ensures recipients solely obtain real emails, avoiding spam. Primarily based on the service supplier, full area authentication.
- Set up e-mail API library: Let’s name our e-mail API – “MyEmailAPI”. Make sure the Python app is put in in your system after which set up MyEmailAPI’s Python SDK utilizing the under command:
pip set up myemailapi
Ship a Plain Textual content Electronic mail
Step 1: Create your mail object and fill within the variables
1 |
import myemailapi |
2 |
|
3 |
# Create a mail object
|
4 |
|
5 |
mailobj = Mail( |
6 |
newsender= Handle(email1=“testmail@area.com”, title=“Take a look at Sender”), |
7 |
to=[Address(email1=“reciever@example.com”, name=“Test Receiver”)], |
8 |
newsubject=“Take a look at e-mail”, |
9 |
newtext=“This is a plain-textual content e-mail.”, |
10 |
)
|
Now, create the e-mail consumer utilizing your API tokens by:
- Opening your e-mail API account
- Discovering API tokens and copying the credentials
Step 2: Ship your message
# Outline e-mail API consumer and ship e-mail
1 |
emailclient = MyEmailAPIClient(newtoken=“new-api-key”) |
2 |
emailclient.ship(mailobj) |
Right here’s the entire code snippet:
1 |
from myemailapi import Mail, EAddress, MyEmailAPIClient |
2 |
mailobj = Mail( |
3 |
# Outline sender handle and title
|
4 |
newsender=Handle(email1=“testmail@area.com”, title=“Take a look at Sender”), |
5 |
# Outline receivers
|
6 |
to=[Address(email1=“receiver@example.com”, name=“Test Receiver”)], |
7 |
# Electronic mail topic
|
8 |
newsubject=“Take a look at e-mail”, |
9 |
# Outline plain textual content
|
10 |
newtext=“Hello,/nThis is a plain-textual content e-mail.”, |
11 |
)
|
12 |
|
13 |
# Outline MyEmailAPIClient utilizing your API keys
|
14 |
emailclient = MyEmailAPIClient(newtoken=“new-api-key”) |
15 |
|
16 |
# Ship your plain-text e-mail
|
17 |
emailclient.ship(mailobj) |
18 |
|
19 |
print(“Congrats! You’ve efficiently despatched your first plain textual content e-mail in Python.”) |
Ship an HTML Electronic mail
Comply with the directions to send an HTML email:
- Specify the HTML Parameter: Specify the ‘html’ parameter for the item – “Mail”. That is the place you’ll hold the HTML content material you create. Electronic mail purchasers that may show HTML will render this e-mail part.
- Fallback Textual content Content material: If an e-mail consumer can’t render HTML content material, the plain textual content you’ll outline inside the e-mail will likely be used because the fallback. That is additionally helpful for end-users preferring pure text-based emails.
Right here’s the total code snippet for sending a Python e-mail with HTML content material:
1 |
from myemailapi import Mail, EAddress, MyEmailAPIClient |
2 |
|
3 |
mailobj = Mail( # Create the Mail object for the HTML e-mail |
4 |
# Outline sender handle and title
|
5 |
newsender=Handle(emailaddress=“testmail@area.com”, title=“Take a look at Sender”), |
6 |
# Outline receivers
|
7 |
to=[Address(emailaddress=“receiver@example.com”, name=“Test Receiver”)], |
8 |
# Outline e-mail topic
|
9 |
newsubject=“HTML e-mail”, |
10 |
# Outline textual content
|
11 |
newtext=“Hello,/nEmail consumer can’t render HTML? Use this fallback textual content.”, |
12 |
html_text=“”” |
13 |
<html> |
14 |
<head> |
15 |
<title>Title</title> |
16 |
</head> |
17 |
|
18 |
<physique> |
19 |
<h1>Hello, there!</h1> |
20 |
<p>This is textual content HTML content material despatched utilizing MyEmailAPI.</p> |
21 |
</physique> |
22 |
</html> |
23 |
“””, |
24 |
)
|
25 |
|
26 |
# Outline MyEmailAPIClient utilizing your API keys
|
27 |
emailclient = MyEmailAPIClient(newtoken=“new-api-key”) |
28 |
|
29 |
# Ship your HTML e-mail
|
30 |
emailclient.ship(mailobj) |
31 |
|
32 |
print(“Congrats! You’ve efficiently despatched your first HTML e-mail.”) |
Ship Electronic mail to A number of Recipients
Comply with the under directions:
- A number of Recipients Configuration: I’ll change the recipient part to arrange the e-mail for extra recipients. As a substitute of utilizing just one ‘to’ handle, we’ll use a number of addresses.
- Setting the ‘To’ subject: Within the under code, we’ll outline two recipient addresses for the ‘To’ field- receiver1@example.com and receiver2@example.com. As well as, we’ll outline names for every recipient – Take a look at Receiver 1 and Take a look at Receiver 2.
Right here’s the entire code for sending an e-mail to a number of recipients in Python:
1 |
from myemailapi import Mail, EAddress, MyEmailAPIClient |
2 |
|
3 |
# Create the Mail object for a number of recipients
|
4 |
mailobj = Mail( |
5 |
# Outline sender handle and title
|
6 |
newsender=Handle(emailaddress=“testmail@area.com”, title=“Take a look at Sender”), |
7 |
# Outline receivers
|
8 |
to=[ |
9 |
Address(emailaddress=“receiver1@example.com”, name=“Test Receiver 1”)], |
10 |
Handle(emailaddress=“receiver2@instance.com”, title=“Take a look at Receiver 2”)], |
11 |
],
|
12 |
# Outline e-mail topic
|
13 |
newsubject=“ This is e-mail topic”, |
14 |
# Outline textual content
|
15 |
newtext=“Howdy, /nThis e-mail has a number of recipients.”, |
16 |
)
|
17 |
|
18 |
# Outline MyEmailAPIClient utilizing your API keys
|
19 |
emailclient = MyEmailAPIClient(newtoken=“new-api-key”) |
20 |
|
21 |
# Ship e-mail
|
22 |
emailclient.ship(mailobj) |
23 |
|
24 |
print(“Congrats! You’ve efficiently despatched emails to a number of recipients in Python.”) |
Ship Electronic mail With Attachments
Comply with the under directions:
- Specify the file path: First, specify the file path for the attachments. The code will learn the file content material as bytes to make sure every attachment has correct encoding. This manner, attachments are transmitted securely over the community.
- Encode in Base64: Guarantee to encode the file content material in base64 to guard it from malicious actors as e-mail protocols lack binary-safe options. Once you encode your file content material, the binary knowledge will likely be transformed into textual content for safe transmission. Use the next technique to encode the file content material:
base64.b64encode
- Create the file Attachment: Create the Attachment class occasion with the next parameters:
- disposition_new: To point the file as an attachment, the ‘disposition_new’ is ready to ‘Disposition.ATTACHMENT’.
- content_new: It represents the file content material encoded in base64
- mimetype_new: The parameter indicators e-mail purchasers concerning the file kind.
Right here’s the entire code:
1 |
from myemailapi import Mail, EAddress, MyEmailAPIClient Attachment, Disposition |
2 |
import base64 |
3 |
from pathlib import Path |
4 |
|
5 |
# Outline information to connect
|
6 |
filepath = Path(“thisis/your/filepath/abc.pdf”) # Insert your file’s title |
7 |
filecontent = filepath.read_bytes() |
8 |
|
9 |
# Base64 is used to encode the content material of the file
|
10 |
encodedcontent = base64.b64encode(filecontent) |
11 |
|
12 |
# Specify the e-mail object with an attachment
|
13 |
mailobj = Mail( |
14 |
# Outline sender handle and title
|
15 |
newsender=Handle(emailaddress=“testmail@area.com”, title=“Take a look at Sender”), |
16 |
# Outline receiver
|
17 |
to=[Address(emailaddress=“receiver@example.com”, name=“Test Receiver”)], |
18 |
# Outline e-mail topic
|
19 |
newsubject=“ Attachment inside!”, |
20 |
# Outline textual content
|
21 |
newtext=“Howdy, /nThis e-mail has an essential attachment.”, |
22 |
# Outline e-mail 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 |
# Outline MyEmailAPIClient utilizing your API keys
|
34 |
emailclient = MyEmailAPIClient(newtoken=“new-api-key”) |
35 |
|
36 |
# Ship e-mail
|
37 |
emailclient.ship(mailobj) |
38 |
|
39 |
print(“Congrats! You’ve efficiently despatched emails with an attachment.”) |
Take a look at Electronic mail Earlier than Sending
Earlier than you ship bulk emails utilizing an e-mail API service, be sure to take a look at it beforehand on a take a look at server. That is much like testing a brand new software or rolling out a brand new characteristic in your app.
An e-mail testing API will work like a third-party net server. You’ll get a safe staging setting the place you may deal with your e-mail site visitors internally and test if the e-mail sending performance is working effective. It’s also possible to detect and resolve bugs and errors earlier than sending your emails to focused recipients. As well as, you may preview and consider your e-mail content material throughout completely different units and e-mail purchasers to be able to optimize your message.
In consequence, you’ll be capable of:
- Ship emails to the proper recipients and improve e-mail deliverability
- Keep away from spamming recipients with too many take a look at emails
- Stop sending emails with damaged hyperlinks, particularly in transactional emails like subscription affirmation emails
- Safeguard your area repute by stopping area blacklisting or getting greater spam scores
Thus, earlier than you ship your emails, ship them to a chosen e-mail handle utilizing an e-mail testing API. View the e-mail content material, test hyperlinks, repair points, after which solely ship your emails to the audience.
Within the under part, I’ll present you easy methods to take a look at an e-mail utilizing a hypothetical e-mail testing API – ‘EtestAPI’. Right here’s easy methods to get began step-by-step:
- Connect with the EtestAPI consumer
- Outline e-mail content material – topic, textual content, attachments (if any), sender, and receiver(s)
- Generate a POST request to EtestAPI utilizing your knowledge and API token.
Right here’s the total code to check your e-mail utilizing EtestAPI:
1 |
# Import ‘json’ and ‘requests’ libraries for dealing with JSON knowledge and HTTP requests
|
2 |
import requests |
3 |
import json |
4 |
|
5 |
# Outline a operate ‘test_my_email’ with parameters for e-mail testing
|
6 |
def test_my_email(etestapi_token1, inbox_id1, sender_email1, recipient_email1, topic, textual content): |
7 |
url = f"https://api.etestapi.com/v1/inboxes/{inbox_id1}/messages" |
8 |
headers = { |
9 |
"Authorization": f"Bearer {etestapi_token1}", |
10 |
"Content material-Sort": "software/json", |
11 |
}
|
12 |
|
13 |
knowledge = { |
14 |
"from": [{“sender_email1”: “sender@domain.com”, “name”: “Test Sender”}], |
15 |
"to": [{“recipient_email1”: “receiver@example.com”, “name”: “Test Receiver”}], |
16 |
"topic": “Electronic mail Take a look at”, |
17 |
"textual content": “Hello,/nLet’s carry out e-mail testing”, |
18 |
}
|
19 |
|
20 |
|
21 |
# Convert knowledge to a JSON string
|
22 |
json_data = json.dumps(knowledge) |
23 |
|
24 |
# make a POST request utilizing ‘requests.put up’ to ship your e-mail to EtestAPI and get the response in JSON
|
25 |
response = requests.put up(url, headers=headers, json_data) |
26 |
|
27 |
if response.status_code == 200: |
28 |
print("Congrats! Your e-mail take a look at is profitable!") |
29 |
print("The take a look at e-mail is shipped to EtestAPI inbox.") |
30 |
else: |
31 |
print(f"Take a look at e-mail failed: {response.status_code}") |
32 |
print(response.textual content) |
Clarification:
- ‘url’: API endpoint URL is constructed
- ‘headers’: Headers are arrange, defining the kind of content material and API token
- response.standing.code: It helps you test whether or not your e-mail was efficiently despatched to the e-mail take a look at API.
Summing Up
Utilizing a dependable and safe e-mail API resolution lets you ship emails quicker, with out hassles. Should you run a enterprise, an e-mail API will aid you automate the method. Thus, you may ship extremely personalised and bulk emails shortly with a number of strains of code as we’ve talked about above.
We additionally advocate you seek advice from the Python documentation and the e-mail API resolution you favor. Maintain experimenting with new code and exploring email-sending functionalities.