Article image Sending Automated Emails with Python

22. Sending Automated Emails with Python

Page 42 | Listen in audio

In today's fast-paced digital world, communication is key, and email remains one of the most prevalent forms of professional and personal communication. Automating email tasks can save a significant amount of time and effort, especially when dealing with repetitive tasks such as sending newsletters, updates, or notifications. Python, with its robust libraries and easy-to-understand syntax, offers excellent tools for automating email tasks.

Understanding the Basics of Email Automation

Email automation involves programming a system to send emails automatically based on predefined triggers or schedules. The process typically involves composing the email content, specifying recipients, and sending the emails through a mail server. Python provides several libraries such as smtplib, email, and yagmail that simplify these tasks.

Setting Up Your Environment

Before diving into code, ensure you have Python installed on your machine. You can download it from the official Python website. Additionally, you might want to use a virtual environment to manage dependencies for your project. Virtual environments help in maintaining project-specific libraries and avoid conflicts.

python -m venv email_automation_env
source email_automation_env/bin/activate  # On Windows use `email_automation_env\Scripts\activate`

Once your environment is set up, you can install the necessary libraries using pip:

pip install yagmail
pip install keyring

Using SMTP with Python

The smtplib library is part of Python's standard library and provides a simple way to send emails using the Simple Mail Transfer Protocol (SMTP). Here's a basic example of how to send an email using smtplib:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(subject, body, to_email):
    from_email = "[email protected]"
    password = "your_password"

    # Set up the server
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()

    # Login to the email account
    server.login(from_email, password)

    # Create the email
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    # Send the email
    server.send_message(msg)
    server.quit()

send_email("Test Subject", "This is a test email", "[email protected]")

In this script, we use Gmail's SMTP server. Replace [email protected] and your_password with your actual email address and password. Note that for Gmail, you may need to enable "Less secure app access" in your account settings or use an app-specific password if you have two-factor authentication enabled.

Enhancing Email Automation with Yagmail

While smtplib is powerful, it can be cumbersome for more complex tasks. Yagmail is a third-party library that simplifies the process of sending emails. It integrates with Python’s keyring module to securely store and retrieve email credentials, making it both secure and convenient.

Here's how you can send an email using Yagmail:

import yagmail

def send_email(subject, body, to_email):
    yag = yagmail.SMTP('[email protected]')
    yag.send(
        to=to_email,
        subject=subject,
        contents=body,
    )

send_email("Test Subject", "This is a test email", "[email protected]")

Before running this script, you need to set up your email credentials using keyring. This can be done via the command line:

yagmail.register('[email protected]', 'your_password')

Once registered, Yagmail will automatically retrieve your credentials from the keyring, enhancing security by not hardcoding passwords into your scripts.

Advanced Email Automation Techniques

With the basics covered, let's explore some advanced techniques to make your automated emails more dynamic and powerful.

Sending HTML Emails

Plain text emails are functional, but HTML emails allow for richer content and a more professional appearance. Both smtplib and yagmail support sending HTML emails. Here's an example using Yagmail:

html_content = """
<h1>Welcome to Our Newsletter</h1>
<p>Thank you for subscribing to our newsletter. We are excited to have you on board!</p>
<p>Best regards,<br>The Team</p>
"""

send_email("Welcome!", html_content, "[email protected]")

Simply pass the HTML string as the contents parameter, and Yagmail will handle the rest.

Attaching Files

Sending attachments is a common requirement in email automation. Yagmail makes this easy by allowing you to pass file paths as part of the contents parameter:

def send_email_with_attachment(subject, body, to_email, attachment_path):
    yag = yagmail.SMTP('[email protected]')
    yag.send(
        to=to_email,
        subject=subject,
        contents=[body, attachment_path],
    )

send_email_with_attachment("Subject with Attachment", "Please find the attachment.", "[email protected]", "/path/to/file.pdf")

Yagmail will automatically detect the file type and handle the attachment process for you.

Scheduling Automated Emails

To schedule emails to be sent at specific times, you can use Python's schedule library. This library allows you to set up simple job scheduling for periodic tasks.

import schedule
import time

def job():
    send_email("Scheduled Email", "This email was sent automatically", "[email protected]")

# Schedule the job every day at 9:00 am
schedule.every().day.at("09:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(60)  # wait one minute

This script will send an email every day at 9:00 am. You can adjust the schedule to fit your needs, such as sending emails weekly or monthly.

Conclusion

Automating email tasks with Python can significantly enhance productivity by reducing manual effort and errors. Whether you're sending simple notifications or complex HTML newsletters with attachments, Python provides the tools you need to streamline your email processes. By leveraging libraries like smtplib and yagmail, combined with scheduling capabilities, you can create a powerful email automation system tailored to your specific requirements.

As you continue to explore Python's capabilities, you'll find that automating everyday tasks becomes not only feasible but also enjoyable, allowing you to focus on more strategic aspects of your work.

Now answer the exercise about the content:

Which Python library is part of the standard library and provides a simple way to send emails using SMTP?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Sending Automated Emails with Python: Understanding SMTP Protocol

Next page of the Free Ebook:

43Sending Automated Emails with Python: Understanding SMTP Protocol

11 minutes

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text