Friday, September 6, 2024

Send email in Python with API method: a step-by-step guide

Send email in Python with API method: a step-by-step guide

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. 

Setting up Email API 

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:

  • Choose an email API: To get started, choose an email API according to your preferences. Make sure it offers Python SDKs to send automated emails (for example Mailtrap’s Python SDK). 
  • Sign up: Sign up to the chosen email API provider. 
  • Connect and verify your domain: Next, connect and verify your domain with the email API service provider you’ve chosen. If not verified, you will be able to send emails to the account owner’s email address only. 

This ensures recipients only receive genuine emails, avoiding spam. Based on the service provider, complete domain authentication. 

  • Install email API library: Let’s call our email API - “MyEmailAPI”. Ensure the Python app is installed in your system and then install MyEmailAPI’s Python SDK using the below command:

            pip install myemailapi

Send a Plain Text Email 

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:

  1. Opening your email API account 
  2. Finding API tokens and copying the credentials 

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! Youve successfully sent your first plain text email in Python.)

Send an HTML Email 

Follow the instructions to send an HTML email:

  • Specify the HTML Parameter: Specify the ‘html’ parameter for the object - “Mail”. This is where you’ll keep the HTML content you create. Email clients that can display HTML will render this email section.  
  • Fallback Text Content: If an email client can’t render HTML content, the plain text you’ll define inside the email will be used as the fallback. This is also useful for end-users preferring pure text-based emails. 

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 cant render HTML? Use this fallback text.,
12
            html_text=“””
13
            <html>
14
                      <head>
15
                                 <title>Title</title>
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! Youve successfully sent your first HTML email.)

Send Email to Multiple Recipients 

Follow the below instructions:

  • Multiple Recipients Configuration: I’ll change the recipient section to set up the email for more recipients. Instead of using only one ‘to’ address, we’ll use multiple addresses. 
  • Setting the ‘To’ field: In the below code, we’ll define two recipient addresses for the ‘To’ field- receiver1@example.com and receiver2@example.com. In addition, we’ll define names for each recipient - Test Receiver 1 and Test Receiver 2. 

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! Youve successfully sent emails to multiple recipients in Python.)

Send Email With Attachments 

Follow the below instructions: 

  • Specify the file path: First, specify the file path for the attachments. The code will read the file content as bytes to ensure each attachment has proper encoding. This way, attachments are transmitted securely over the network. 
  • Encode in Base64: Ensure to encode the file content in base64 to protect it from malicious actors as email protocols lack binary-safe features. When you encode your file content, the binary data will be converted into text for secure transmission. Use the following method to encode the file content:

            base64.b64encode

  • Create the file Attachment: Create the Attachment class instance with the following parameters:
  1. disposition_new: To indicate the file as an attachment, the ‘disposition_new’ is set to ‘Disposition.ATTACHMENT’. 
  2. content_new: It represents the file content encoded in base64
  3. mimetype_new: The parameter signals email clients about the file type.

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! Youve successfully sent emails with an attachment.)

Test Email Before Sending 

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:

  • Send emails to the right recipients and enhance email deliverability 
  • Avoid spamming recipients with too many test emails
  • Prevent sending emails with broken links, especially in transactional emails like subscription confirmation emails
  • Safeguard your domain reputation by preventing domain blacklisting or getting higher spam scores 

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:

  1. Connect to the EtestAPI client 
  2. Define email content - subject, text, attachments (if any), sender, and receiver(s)
  3. Generate a POST request to EtestAPI using your data and API token.

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,/nLets 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:

  • ‘url’: API endpoint URL is constructed 
  • ‘headers’: Headers are set up, defining the type of content and API token
  • response.status.code: It helps you check whether your email was successfully sent to the email test API.

Summing Up 

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.