DEV Community

Cover image for How to Send Email Notifications using Python? (With Code Examples)
Nik L.
Nik L.

Posted on

How to Send Email Notifications using Python? (With Code Examples)

Email notifications are a great way to keep your users informed about important events or updates in your application, such as a new message, a password reset, or a system failure. There are multiple methods for sending email notifications, and while the process may not be complex, it's important to choose the right approach for your needs.

In this blog, we will be looking at how to send emails using Python with the help of code snippets. We will also compare the SMTP module used in Python with other popular solutions.

Directly Go To:
Send Email using SMTPLIB
Send Email using AWS SES
Send Email using GMAIL API
Send Email using SuprSend

Pre-Requisites
Before getting started with this guide, there are a few things you will need to have to get the most out of it.

  • Python installed on your machine
  • Basic understanding of Python & CLI
  • AWS account setup & understanding of AWS SES
  • Working Suprsend account (with configured vendors)

With these things in mind, you should be ready to get started!

4 Different Ways to Send Email Notifications with Python

This section will discuss four different ways developers can send transactional emails using Python.

Using Python smtplib Module

The smtplib Python module can send emails using the Simple Mail Transfer Protocol (SMTP). SMTP is a protocol that is used to send and receive emails. The smtplib module includes functions that can be used to connect to an SMTP server and send emails. The module also includes functions that can authenticate with an SMTP server.

Benefits of Using smtplib Python Module

There are many benefits of using the smtplib module. For example, you can use smtplib to:

  • Send emails from your Python program
  • Send emails from a script (automated scripts, corn jobs, etc.)
  • Send mass emails
  • Send HTML emails
  • Send attachments

Drawbacks of smtplib Module

There are a few potential drawbacks to using SMTP to send python emails. One is that it can be less reliable than other methods; sometimes, emails sent via SMTP get lost or end up in spam folders.

Additionally, SMTP relies on several complex protocols, making it difficult to configure and troubleshoot. Maintaining and upgrading SMTP servers can also entail additional costs.

Steps To Send Email via SMTP Python Module

You can use MIMEText or EmailMessage module to create and format the message. Below are the steps to send an email using Python with the smtplib and MIMEText module.

  1. - Import the smtplib and MIMEText modules from the email library.
  2. - Create a new MIMEText object and set the body of the email, the sender, the recipient, and the subject.
  3. - Establish a connection to the SMTP server using the smtplib.SMTP() function, passing in the server's hostname as an argument.
  4. - Use the send_message() function to send the email.
  5. - Use the quit() function to close the connection to the server.
  6. - Use a try/except block to catch any exceptions that may be thrown during the sending process.

Code Snippet
Note: Replace the SMTP server address (localhost) with your server address before running the below code.

# Send email to using using smtplib module in Python
import smtplib
from email.mime.text import MIMEText
try:
   message = MIMEText('This is the body of the email.')
   message['From'] = 'email@gmail.com'
   message['To'] = 'hello@gmail.com'
   message['Subject'] = 'A test email'
   mail_server = smtplib.SMTP('localhost')
   mail_server.send_message(message)
   mail_server.quit()
   print('Email sent successfully')
except Exception as e:
   print('Error: ', e)
Enter fullscreen mode Exit fullscreen mode

Transactional Email Service Providers

Transactional Email Service Providers (TESPs) enable businesses to send transactional emails. There are many options to choose from, including Amazon SES, Mailgun, Sendgrid, Postmark, and Sparkpost, each with its own benefits and features.

It's important to select a TESP that meets your needs in terms of pricing, delivery rates, scalability, and support, and also offers a strong API for integration into your system.

Benefits of Transactional Email Service Providers

Transactional Email Service Providers (TESP) offer several advantages over traditional email providers. TESPs are designed to provide a higher level of service and reliability for businesses that rely on email to communicate with their customers.

  • TESPs can provide a cost-effective way to send transactional emails, as they typically charge based on the number of emails sent or received.
  • TESPs typically offer several features that are not available with traditional email providers, such as dedicated IP addresses, real-time monitoring, and delivery reports.

Drawbacks of Transactional Email Service Providers

  • TESPs can be challenging to set up and use, leading to the need for developers
  • TESPs typically offer API-based integration, thus the email content layout, such as HTML templates need to be integrated via APIs.
  • TESPs can be cost-efficient when sending a relatively low volume of emails, yet as the volume increases, it may become an expensive option
  • Poor configuration can lead to emails being sent to spam folders. Certain TESPs may have suboptimal email-sending configurations, such as using IP addresses with a negative reputation that is shared among multiple users.

This section will use Python with AWS SES to send emails. AWS SES is a cloud-based email service that lets you send and receive emails securely. It offers a cost-effective, pay-as-you-go pricing model and provides a scalable, reliable, and secure platform for email delivery.

Steps To Send Email Using AWS SES

We'll use the Boto3 library to interact with AWS SES. Here are the steps followed in AWS SES send email python process.

  1. Import the necessary libraries and modules: boto3 and ClientError from botocore.exceptions.
  2. Define the send_email() function, which takes six arguments: the sender and recipient email addresses, the subject and body of the email, and the name of the AWS region where the SES service is located.
  3. Create a new client for the SES service in the specified region using the boto3.client() function.
  4. Use the send_email() method of the SES client to send the email, specifying the contents of the email (subject, body, recipient) in the Destination and Message parameters.
  5. Catch any errors that occur when trying to send the email using a try-except block and print the error message.
  6. If the email is sent successfully, return True. Otherwise, return False.

Code Snippet

#  Send email using AWS SES
import boto3
from botocore.exceptions import ClientError
def send_email(sender, recipient, subject, body_text, body_html, region):
   # The HTML body of the email.
   BODY_HTML = body_html
   # The character encoding for the email.
   CHARSET = "UTF-8"
   # Create a new SES resource and specify a region.
   client = boto3.client(
       'ses',
       region_name=region,
       aws_access_key_id=access_key,
       aws_secret_access_key=secret_key   
   )

   # Try to send the email.
   try:
       # Provide the contents of the email.
       response = client.send_email(
           Destination={
               'ToAddresses': [
                   recipient,
               ],
           },
           Message={
               'Body': {
                   'Html': {
                       'Charset': CHARSET,
                       'Data': BODY_HTML,
                   },
                   'Text': {
                       'Charset': CHARSET,
                       'Data': body_text,
                   },
               },
               'Subject': {
                   'Charset': CHARSET,
                   'Data': subject,
               },
           },
           Source=sender,
       )
   except ClientError as e:
       print(e.response['Error']['Message'])
   else:
       print("Email sent! Message ID:"),
       print(response['MessageId'])
       return True
   return False


Enter fullscreen mode Exit fullscreen mode

Using Suprsend

Suprsend is a platform that allows developers to create and manage notifications across multiple channels, such as email, SMS, push notifications, inbox messages, and chat.

SuprSend workflows simplify the process of building and managing complex notifications, as well as performance tracking to monitor the effectiveness of the messages. Using a single API, streamlines the process of sending notifications, and eliminates the need for developers to write their own notification service layer.
Benefits of using Suprsend:

It is highly scalable and can be used to develop notifications for any number of users.

SuprSend has built-in integration with TESP(s) SMTP and Gmail SMTP, so developers don’t have to do setup or point-to-point API integration with them. This feature allows for seamless switching between vendors, without the constraint of being locked into a specific one.

SuprSend's Python SDK allows developers to trigger multi-channel notifications with a single trigger easily. This can be extremely useful for applications that communicate with multiple channels or devices.

Suprsend doesn't require any infrastructure setup or maintenance. It's a cloud-based solution that's easy to use and scale.
Steps To Send Emails Using SuprSend

Installing Suprsend Python SDK
To get started, first install Suprsend Python SDK using the following command:

pip install suprsend-py-sdk

To send notifications using Suprsend, you’ll need a Workspace Key & Secret (for authentication). You can modify the default workflow and notification template or can create a new workflow and template.

Note: We have created a sample template and workflow on the SuprSend platform for this tutorial.

Python Code to Send Email using Suprsend

from suprsend import Suprsend
from suprsend import Workflow

supr_client = Suprsend("spxxxxxxxxxx", "wscxxxxxxxxxx")

# Prepare Workflow body
workflow_body = {
 "name": "hello email",
 "template": "email-template",
 "notification_category": "transactional",
 "users": [
   {
     "distinct_id": "abc@company.xyz",
     "email": "abc@company.xyz",
   }
 ],
 "data": {
   "name": "User",
   "height": 190
 }
}

wf = Workflow(body=workflow_body)
 # Trigger workflow
response = supr_client.trigger_workflow(wf)
print(response) // {'success': True, 'status': 'success', 'status_code': 202, 'message': 'OK'}

Enter fullscreen mode Exit fullscreen mode

Adding Attachments with Email

Adding python email attachments using Suprsend is a piece of cake. Just add the following code snippets to add an attachment via a file path directly. The workflow object will look something like this:


workflow_body = {...}

wf = Workflow(body=workflow_body)
file_path = "/suprsend/user/invoice.pdf"
wf_instance.add_attachment(file_path)
 # Trigger workflow
response = supr_client.trigger_workflow(wf)
print(response) // {'success': True, 'status': 'success', 'status_code': 202, 'message': 'OK'}

Enter fullscreen mode Exit fullscreen mode

Using Gmail SMTP

Gmail is one of the most popular email providers and for a good reason. It's free, it's easy to use, and it's packed with features. But did you know that you can also use Gmail with Python?

Yes, it's true! You can use the Gmail API to send and receive emails with Python. And the best part is that it's not even that difficult. This section will show you how to send emails using Gmail with Python.

Benefits of Gmail API
There are many benefits to using the Gmail API to send emails. Perhaps the most obvious benefit is that it allows you to send emails directly from your Gmail account, which can be very convenient.

Additionally, the Gmail API can provide a more reliable and responsive experience than other email-sending methods. And because the Gmail API is integrated with other Google services, it can offer some unique features and advantages that other email providers cannot match.

Drawbacks of Gmail API
There are a few drawbacks to using the Gmail API:

To use Gmail API, you have to use email credentials (username & password) which is less secure. Maintaining the account will always be an issue if you plan to use a separate service account.

Gmail has the following hard limits on sending emails:

  • Maximum messages per day: 2,000 (1,500 for multi-send & 500 for a trial account)
  • Total recipients per day: 10,000

Companies avoid using Gmail as a scalable email solution because of its drawbacks.

Learn more about Gmail API usage limits.

Code Snippet

# Send email to using Gmail SMTP server
import smtplib
from email.mime.text import MIMEText

def send_email(email, name, height):
   from_email = "abc@gmail.com"
   from_password = "password"
   to_email = email


   subject = "User Height Data"
   message = "Hey %s, your height is <strong>%s</strong>." % (name, height)


   msg = MIMEText(message, 'html')
   msg['Subject'] = subject
   msg['To'] = to_email
   msg['From'] = from_email


   # Create SMTP session for sending the mail
   gmail = smtplib.SMTP('smtp.gmail.com', 587)
   gmail.ehlo()
   gmail.starttls()
   # Login to gmail account
   gmail.login(from_email, from_password)
   # Send mail
   gmail.send_message(msg)


if __name__ == '__main__':
   send_email("hello@gmail.com", "John", "180")
Enter fullscreen mode Exit fullscreen mode

Conclusion

And with that, we hope we have been able to give you a comprehensive guide on using Python to send emails. If you are looking for a multi-channel scalable notification solution and a way to make your development process more streamlined and efficient, check out SuprSend.

Top comments (1)

Collapse
 
nikl profile image
Nik L.

Get 10000 notifications per month here: SuprSend