Create a Python program to automate sending emails with attachments.
- User
Create a Python program to automate sending emails with attachments.
- Assistant
Creating email automation script
I need to create a Python program that automates sending emails with attachments, likely using the smtplib and email.mime libraries. I want to provide a clear yet concise program, so I’ll avoid being overly verbose while covering all key elements.
Considering security, I should discuss modern methods like OAuth2 versus app passwords, but I'll stick to SMTPS with login/password. I’ll make it generic but include a Gmail example, focusing on a function that sends an email with attachments and uses the mimetypes module for handling file types.Developing email script details
I want to focus on illustrating the script without diving into command-line interface or scheduling specifics, though I might mention cron briefly. First, I'll outline prerequisites: enabling "less secure apps" for Gmail or creating an app password for two-factor authentication, making sure I don't suggest insecure practices.
Next, I'll provide a basic script structure in Python that includes handling attachments. I’ll ensure robust functionality with
mimetypesto determine file types and use a context manager forsmtplib.SMTP_SSLto enhance security. The attachments will be added using a dedicated function.Simplifying email functionalitiesI want to keep this program straightforward, avoiding complexities like logging. While I could include an example for O365, I'll mainly keep it generic. It's important to remember that I can't facilitate spam sending, as that falls under user responsibility regarding compliance.
I could provide both plain text and HTML options for emails, but I'll focus on a simple text version to stay concise. Lastly, I need to remind users not to hardcode passwords and recommend using environment variables instead. Below is a complete, minimal example of a Python script that sends emails with one or more attachments via SMTP.
It uses:
smtplibfor SMTPemail.message.EmailMessagefor building the mailmimetypesto set the correct content type for attachments
You can adapt it to Gmail, Outlook, etc. by changing the SMTP settings.
1. Install Python requirements
These are all in the standard library, so no extra install is needed:
python3 your_script.py
2. Example script:
send_email_with_attachments.pyimport os import smtplib import mimetypes from email.message import EmailMessage from pathlib import Path def send_email_with_attachments( subject: str, body: str, sender_email: str, recipient_emails: list[str], smtp_server: str, smtp_port: int, smtp_username: str, smtp_password: str, attachment_paths: list[str] | None = None, use_tls: bool = True, ): """ Send an email with optional attachments. :param subject: Email subject :param body: Email body (plain text) :param sender_email: From address :param recipient_emails: List of recipient addresses :param smtp_server: SMTP server hostname (e.g., 'smtp.gmail.com') :param smtp_port: SMTP port (e.g., 587 for TLS, 465 for SSL) :param smtp_username: SMTP account username (often same as sender_email) :param smtp_password: SMTP account password or app password :param attachment_paths: List of file paths to attach :param use_tls: If True, use STARTTLS; if False and port is 465, uses SSL directly """ # Build the email msg = EmailMessage() msg["Subject"] = subject msg["From"] = sender_email msg["To"] = ", ".join(recipient_emails) msg.set_content(body) # Add attachments, if any attachment_paths = attachment_paths or [] for file_path in attachment_paths: path = Path(file_path) if not path.is_file(): print(f"Warning: attachment not found, skipping: {file_path}") continue # Guess MIME type ctype, encoding = mimetypes.guess_type(str(path)) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) with open(path, "rb") as f: file_data = f.read() msg.add_attachment( file_data, maintype=maintype, subtype=subtype, filename=path.name, ) # Send the email via SMTP if use_tls and smtp_port == 465: # If using port 465, typically SSL is used directly use_tls = False if use_tls: # Typical: port 587 + STARTTLS with smtplib.SMTP(smtp_server, smtp_port) as server: server.ehlo() server.starttls() server.ehlo() server.login(smtp_username, smtp_password) server.send_message(msg) else: # Typical: port 465 + SSL with smtplib.SMTP_SSL(smtp_server, smtp_port) as server: server.login(smtp_username, smtp_password) server.send_message(msg) if __name__ == "__main__": # Example usage: # # For real usage, you should NOT hardcode credentials. # Use environment variables or a secure secrets manager instead. # # Example (Linux/macOS): # export SMTP_USER="your_email@example.com" # export SMTP_PASS="your_app_password" # # Then run: # python send_email_with_attachments.py SMTP_SERVER = "smtp.gmail.com" # e.g. 'smtp.gmail.com' or your provider SMTP_PORT = 587 # 587 (TLS) or 465 (SSL) SMTP_USER = os.environ.get("SMTP_USER") SMTP_PASS = os.environ.get("SMTP_PASS") if not SMTP_USER or not SMTP_PASS: raise SystemExit("Please set SMTP_USER and SMTP_PASS environment variables.") sender = SMTP_USER recipients = ["recipient1@example.com", "recipient2@example.com"] subject = "Automated report with attachments" body = "Hello,\n\nPlease find the attached files.\n\nBest regards,\nYour Script" attachments = [ "report.pdf", "image.png", # add more paths if needed ] send_email_with_attachments( subject=subject, body=body, sender_email=sender, recipient_emails=recipients, smtp_server=SMTP_SERVER, smtp_port=SMTP_PORT, smtp_username=SMTP_USER, smtp_password=SMTP_PASS, attachment_paths=attachments, use_tls=True, ) print("Email sent.")
3. Provider-specific notes (brief)
-
Gmail
- If 2FA is enabled, create an App Password in your Google account and use that as
SMTP_PASS. - SMTP settings:
- Server:
smtp.gmail.com - Port:
587(TLS) or465(SSL)
- Server:
- If 2FA is enabled, create an App Password in your Google account and use that as
-
Outlook/Office 365 (common case)
- Server:
smtp.office365.com - Port:
587(TLS)
- Server:
If you tell me your email provider and how you’d like to trigger this (e.g., scheduled daily, triggered by a script, etc.), I can tailor the script further (CLI arguments, HTML body, logging, etc.).