Friday, October 4, 2024
HomeCSSShip electronic mail in Python with API technique: a step-by-step information

Ship electronic mail in Python with API technique: a step-by-step information


If you wish to ship emails in Python, use a dependable and safe electronic mail API answer. On this article, you’ll be taught the step-by-step strategy of sending emails in Python utilizing the API technique. 

Organising E-mail API 

To streamline electronic mail sending in Python, you should utilize a transactional electronic mail service reminiscent of Mailtrap, Gmail API, Sendgrid, and many others.  And, an API additionally permits you to automate a lot of electronic mail sending 

Now, I’ll present you ship various kinds of emails (plain textual content, electronic mail with attachments, HTML emails) and electronic mail a number of recipients in Python utilizing an electronic mail API Earlier than that, let’s perceive arrange an electronic mail API:

  • Select an electronic mail API: To get began, select an electronic mail API based on your preferences. Be sure it provides Python SDKs to ship automated emails (for instance Mailtrap’s Python SDK). 
  • Enroll: Signal as much as the chosen electronic 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 electronic mail deal with solely. 

This ensures recipients solely obtain real emails, avoiding spam. Based mostly on the service supplier, full area authentication. 

  • Set up electronic mail API library: Let’s name our electronic 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 E-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= Tackle(email1=testmail@area.com, title=Check Sender),
7
        to=[Address(email1=reciever@example.com, name=Test Receiver)], 
8
        newsubject=Check electronic mail,
9
        newtext=This is a plain-textual content electronic mail.,
10
)

Now, create the e-mail consumer utilizing your API tokens by:

  1. Opening your electronic mail API account 
  2. Discovering API tokens and copying the credentials 

Step 2: Ship your message

# Outline electronic mail API consumer and ship electronic mail

1
emailclient = MyEmailAPIClient(newtoken=new-api-key)
2
emailclient.ship(mailobj)

Right here’s the whole code snippet:

1
from myemailapi import Mail, EAddress, MyEmailAPIClient     
2
mailobj = Mail(
3
             # Outline sender deal with and title
4
             newsender=Tackle(email1=testmail@area.com, title=Check Sender),
5
             # Outline receivers
6
             to=[Address(email1=receiver@example.com, name=Test Receiver)], 
7
             # E-mail topic
8
            newsubject=Check electronic mail,
9
            # Outline plain textual content
10
            newtext=Hello,/nThis is a plain-textual content electronic mail.,
11
 )
12

13
# Outline MyEmailAPIClient utilizing your API keys 
14
emailclient = MyEmailAPIClient(newtoken=new-api-key)
15

16
# Ship your plain-text electronic mail
17
emailclient.ship(mailobj)
18

19
print(Congrats! Youve efficiently despatched your first plain textual content electronic mail in Python.)

Ship an HTML E-mail 

Observe the directions to ship an HTML electronic mail:

  • Specify the HTML Parameter: Specify the ‘html’ parameter for the item – “Mail”. That is the place you’ll maintain the HTML content material you create. E-mail shoppers that may show HTML will render this electronic mail part.  
  • Fallback Textual content Content material: If an electronic mail consumer can’t render HTML content material, the plain textual content you’ll outline inside the e-mail shall 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 electronic mail with HTML content material:

1
from myemailapi import Mail, EAddress, MyEmailAPIClient     
2

3
mailobj = Mail(                         # Create the Mail object for the HTML electronic mail
4
             # Outline sender deal with and title
5
             newsender=Tackle(emailaddress=testmail@area.com, title=Check Sender),
6
             # Outline receivers
7
             to=[Address(emailaddress=receiver@example.com, name=Test Receiver)], 
8
             # Outline electronic mail topic
9
            newsubject=HTML electronic mail,
10
            # Outline textual content
11
            newtext=Hello,/nEmail consumer cant 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 electronic mail
30
emailclient.ship(mailobj)
31

32
print(Congrats! Youve efficiently despatched your first HTML electronic mail.)

Ship E-mail to A number of Recipients 

Observe the under directions:

  • A number of Recipients Configuration: I’ll change the recipient part to arrange the e-mail for extra recipients. As an alternative of utilizing just one ‘to’ deal with, we’ll use a number of addresses. 

  • Setting the ‘To’ area: Within the under code, we’ll outline two recipient addresses for the ‘To’ field- receiver1@instance.com and receiver2@instance.com. As well as, we’ll outline names for every recipient – Check Receiver 1 and Check Receiver 2. 

Right here’s the whole code for sending an electronic 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 deal with and title
6
               newsender=Tackle(emailaddress=testmail@area.com, title=Check Sender),
7
               # Outline receivers
8
              to=[
9
                    Address(emailaddress=receiver1@example.com, name=Test Receiver 1)],
10
                    Tackle(emailaddress=receiver2@instance.com, title=Check Receiver 2)], 
11
              ],
12
             # Outline electronic mail topic
13
             newsubject= This is electronic mail topic,
14
             # Outline textual content
15
             newtext=Whats up, /nThis electronic 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 electronic mail
22
emailclient.ship(mailobj)
23

24
print(Congrats! Youve efficiently despatched emails to a number of recipients in Python.)

Ship E-mail With Attachments 

Observe 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 electronic mail protocols lack binary-safe options. Whenever you encode your file content material, the binary information shall 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:

  1. disposition_new: To point the file as an attachment, the ‘disposition_new’ is ready to ‘Disposition.ATTACHMENT’. 
  2. content_new: It represents the file content material encoded in base64
  3. mimetype_new: The parameter alerts electronic mail shoppers in regards to the file kind.

Right here’s the whole code:

1
from myemailapi import Mail, EAddress, MyEmailAPIClient Attachment, Disposition
2
import base64
3
from pathlib import Path
4

5
# Outline recordsdata 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 deal with and title
15
               newsender=Tackle(emailaddress=testmail@area.com, title=Check Sender),
16
               # Outline receiver
17
              to=[Address(emailaddress=receiver@example.com, name=Test Receiver)],
18
              # Outline electronic mail topic
19
             newsubject= Attachment inside!”,
20
             # Outline textual content
21
             newtext=Whats up, /nThis electronic mail has an necessary attachment.,
22
             # Outline electronic 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 electronic mail
37
emailclient.ship(mailobj)
38

39
print(Congrats! Youve efficiently despatched emails with an attachment.)

Check E-mail Earlier than Sending 

Earlier than you ship bulk emails utilizing an electronic 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 utility or rolling out a brand new characteristic in your app. 

An electronic mail testing API will work like a third-party net server. You’ll get a safe staging surroundings the place you’ll be able to deal with your electronic mail site visitors internally and verify if the e-mail sending performance is working positive. You may also detect and resolve bugs and errors earlier than sending your emails to focused recipients. As well as, you’ll be able to preview and consider your electronic mail content material throughout totally different units and electronic mail shoppers with a purpose to optimize your message. 

Because of this, you’ll have the ability to:

  • Ship emails to the best recipients and improve electronic 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 popularity by stopping area blacklisting or getting increased spam scores 

Thus, earlier than you ship your emails, ship them to a chosen electronic mail deal with utilizing an electronic mail testing API. View the e-mail content material, verify hyperlinks, repair points, after which solely ship your emails to the target market. 

Within the under part, I’ll present you take a look at an electronic mail utilizing a hypothetical electronic mail testing API – ‘EtestAPI’. Right here’s get began step-by-step:

  1. Connect with the EtestAPI consumer 
  2. Outline electronic mail content material – topic, textual content, attachments (if any), sender, and receiver(s)
  3. Generate a POST request to EtestAPI utilizing your information and API token.

Right here’s the total code to check your electronic mail utilizing EtestAPI:

1
# Import ‘json’ and ‘requests’ libraries for dealing with JSON information and HTTP requests
2
import requests
3
import json
4

5
# Outline a operate ‘test_my_email’ with parameters for electronic 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": "utility/json",
11
    }
12
    
13
    information = {
14
        "from": [{sender_email1: sender@domain.com, name: Test Sender}],
15
        "to": [{recipient_email1: receiver@example.com, name: Test Receiver}],
16
        "topic": E-mail Check,
17
        "textual content": Hello,/nLets carry out electronic mail testing,
18
    }
19
    
20

21
    # Convert information to a JSON string
22
    json_data = json.dumps(information)
23

24
    # make a POST request utilizing ‘requests.put up’ to ship your electronic 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 electronic mail take a look at is profitable!")
29
        print("The take a look at electronic mail is shipped to EtestAPI inbox.")
30
    else:
31
        print(f"Check electronic 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 verify whether or not your electronic mail was efficiently despatched to the e-mail take a look at API.

Summing Up 

Utilizing a dependable and safe electronic mail API answer permits you to ship emails sooner, with out hassles. For those who run a enterprise, an electronic mail API will assist you to automate the method. Thus, you’ll be able to ship extremely customized and bulk emails rapidly with a number of traces of code as we’ve talked about above. 

We additionally advocate you consult with the Python documentation and the e-mail API answer you like. Hold experimenting with new code and exploring email-sending functionalities.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments