Reusable Python Code Modules, Part 6 - Notifications - Email
Keeping Users Informed: Implementing Reusable Email Notification Modules
Email notifications are essential for user engagement, transactional messaging, and alerting users about important events. This guide covers how to structure reusable email notification modules in Python using Flask, manage email sending efficiently, and integrate common libraries. We will explore common email libraries, compare their features, and provide practical examples and code snippets.
Common Libraries and Tools
1. Flask-Mail
Flask-Mail is a Flask extension that provides a simple interface to set up and send emails
Key Features
Ease of Integration: Easily integrates with Flask applications
Support for Multiple Recipients: Allows sending emails to multiple recipients.
Attachment Support: Enables sending attachments with emails
Configuration Flexibility: Provides multiple configuration options for different email backends
2. Flask-Mailman
Flask-Mailman is a fork of Flask-Mail that aims to provide a more modern and actively maintained alternative
Key Features
Enhanced Attachment Support: Improved handling of email attachments
HTML and Plain Text Emails: Supports sending both HTML and plain text versions of emails
Improved Backend Integration: Provides better integration with various email backends
Compatibility: Compatible with Flask-Mail but offers additional features
3. yagmail
yagmail is a user-friendly SMTP client for sending emails with Gmail
Key Features
Simple Configuration: Easy to set up and configure with Gmail
Inline Attachments: Allows embedding attachments directly in the email body
OAuth2 Support: Supports OAuth2 for secure authentication with Gmail
HTML Support: Enables sending HTML emails with inline images
https://mailtrap.io/blog/yagmail-tutorial
4. SendGrid
SendGrid is a cloud-based email service that offers a comprehensive API for sending emails
Key Features
Scalability: Handles large volumes of emails with ease
Detailed Analytics: Provides insights and analytics on email delivery and engagement
Template Support: Supports reusable email templates for consistent email formatting
SMTP and API: Offers both SMTP and RESTful API for sending emails
Comparison
Flask-Mail: Best for simple email sending needs with easy Flask integration
Flask-Mailman: Ideal for applications requiring enhanced attachment handling and better backend integration
yagmail: Suitable for applications using Gmail with simple configuration and OAuth2 support
SendGrid: Best for scalable email sending with advanced features like analytics and templates
Examples
Example 1: Flask-Mail
Setup:
$ pip install Flask-Mail
Configuration:
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.example.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'your_username'
app.config['MAIL_PASSWORD'] = 'your_password'
mail = Mail(app)
Usage:
@app.route('/send-email')
def send_email():
msg = Message('Hello', sender='your@example.com', recipients=['user@example.com'])
msg.body = 'This is a test email sent from Flask-Mail'
mail.send(msg)
return 'Email sent successfully'
Example 2: Flask-Mailman
Setup:
$ pip install Flask-Mailman
Configuration:
from flask import Flask
from flask_mailman import Mail, EmailMessage
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.example.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'your_username'
app.config['MAIL_PASSWORD'] = 'your_password'
mail = Mail(app)
Usage:
@app.route('/send-email')
def send_email():
msg = EmailMessage(
subject='Hello',
to=['user@example.com'],
body='This is a test email sent from Flask-Mailman',
)
mail.send(msg)
return 'Email sent successfully'
Example 3: yagmail
Setup:
$ pip install yagmail
Configuration:
import yagmail
yag = yagmail.SMTP('your_email@gmail.com', 'your_password')
Usage:
def send_email():
yag.send(
to='user@example.com',
subject='Hello',
contents='This is a test email sent from yagmail'
)
return 'Email sent successfully'
Example 4: SendGrid
Setup:
$ pip install sendgrid
Configuration:
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
def send_email():
message = Mail(
from_email='your@example.com',
to_emails='user@example.com',
subject='Hello',
html_content='<strong>This is a test email sent from SendGrid</strong>'
)
try:
sg = SendGridAPIClient(SENDGRID_API_KEY)
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(str(e))
return 'Email sent successfully'