Search This Blog

Automating Email with Python

 

Automating Email with Python

Email automation is crucial for sending reports, alerts, notifications, and newsletters. Python provides libraries such as smtplib for sending emails, imaplib for reading emails, and email for formatting email messages.


Installing Required Libraries

pip install yagmail
  • smtplib: Sends emails via SMTP servers.
  • imaplib: Retrieves emails from mail servers.
  • email: Formats and parses email messages.
  • yagmail: Simplifies email sending with attachments.

Sending Emails with SMTP

Basic Email with smtplib

import smtplib
from email.mime.text import MIMEText

# Email details
sender_email = "your_email@gmail.com"
receiver_email = "recipient@example.com"
subject = "Automated Email"
body = "Hello, this is an automated email from Python."

# Create message
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = sender_email
msg["To"] = receiver_email

# Send email
with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls()
    server.login(sender_email, "your_password")
    server.sendmail(sender_email, receiver_email, msg.as_string())

print("Email sent successfully.")

Sending Emails with Attachments

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

# Email setup
sender_email = "your_email@gmail.com"
receiver_email = "recipient@example.com"
subject = "Automated Email with Attachment"

# Create email message
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = subject

# Attach file
filename = "document.pdf"
with open(filename, "rb") as attachment:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

encoders.encode_base64(part)
part.add_header("Content-Disposition", f"attachment; filename={filename}")
msg.attach(part)

# Send email
with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls()
    server.login(sender_email, "your_password")
    server.sendmail(sender_email, receiver_email, msg.as_string())

print("Email with attachment sent successfully.")

Reading Emails from Inbox

Connecting to an Email Server

import imaplib

# Connect to email server
mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login("your_email@gmail.com", "your_password")
mail.select("inbox")

print("Connected to inbox.")

Fetching Unread Emails

import email

# Search for unread emails
status, messages = mail.search(None, 'UNSEEN')

for num in messages[0].split():
    status, msg_data = mail.fetch(num, "(RFC822)")
    raw_email = msg_data[0][1]

    # Parse email
    msg = email.message_from_bytes(raw_email)
    print(f"From: {msg['From']}")
    print(f"Subject: {msg['Subject']}")

mail.close()
mail.logout()

Sending Emails Using yagmail

import yagmail

# Setup yagmail
yag = yagmail.SMTP("your_email@gmail.com", "your_password")

# Send email
yag.send(
    to="recipient@example.com",
    subject="Automated Email",
    contents="This is a test email using yagmail.",
    attachments="report.pdf"
)

print("Email sent successfully.")

Automating Email Reports

import yagmail

# Define recipients and message
recipients = ["recipient1@example.com", "recipient2@example.com"]
subject = "Weekly Sales Report"
body = "Attached is the latest sales report."

# Send email with report attachment
yag.send(to=recipients, subject=subject, contents=body, attachments="sales_report.xlsx")

print("Sales report email sent.")

Conclusion

This section covered sending and reading emails using Python, including sending attachments and automating reports. These techniques are useful for email notifications, alerts, and scheduled reports.

Would you like additional examples or modifications?

Popular Posts