(toc)

Sending Email Using SMTP in Python

Python provides a built-in library called smtplib to send emails using the Simple Mail Transfer Protocol (SMTP). With this library, you can connect to an email server, authenticate, and send emails programmatically.

This guide will walk you through the steps to send emails using Python.


Steps to Send Email Using SMTP

  1. Set Up SMTP Server: Connect to the email provider’s SMTP server (e.g., Gmail, Yahoo).
  2. Authenticate: Log in using your email and password (use app-specific passwords or OAuth for added security).
  3. Compose the Email: Define the sender, recipient(s), subject, and message body.
  4. Send the Email: Use the smtplib library to send the email.

Code Example: Sending a Simple Email

Here’s a basic example of sending an email using Python.

Code:


import smtplib from email.mime.text import MIMEText # Email configuration SMTP_SERVER = "smtp.gmail.com" SMTP_PORT = 587 EMAIL = "your_email@gmail.com" # Your email address PASSWORD = "your_password" # Your email password (use app-specific password for Gmail) # Create the email subject = "Test Email" body = "Hello! This is a test email sent from Python." recipient = "recipient_email@gmail.com" # Format the email message = MIMEText(body, "plain") message["Subject"] = subject message["From"] = EMAIL message["To"] = recipient try: # Connect to the SMTP server with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server: server.starttls() # Start TLS (Transport Layer Security) encryption server.login(EMAIL, PASSWORD) # Log in to the email account server.send_message(message) # Send the email print("Email sent successfully!") except Exception as e: print(f"Error: {e}")


Breaking Down the Code

  1. SMTP Configuration:

    • SMTP_SERVER: The SMTP server address (e.g., smtp.gmail.com for Gmail).
    • SMTP_PORT: The port number (usually 587 for TLS or 465 for SSL).
  2. Authentication:

    • Use your email and password. For Gmail, enable “Allow less secure apps” or generate an app-specific password.
  3. Message Formatting:

    • MIMEText: Creates a plain text email body. You can also use MIMEText(body, "html") for HTML emails.
  4. TLS Encryption:

    • starttls(): Secures the connection by encrypting the communication with the server.
  5. Send the Email:

    • server.send_message(message): Sends the email to the specified recipient(s).

Sending HTML Emails

To send an email with HTML content, change the email body type to "html".

Example: HTML Email


from email.mime.text import MIMEText # Email content html_body = """ <html> <body> <h1>Hello!</h1> <p>This is an <b>HTML email</b> sent from Python.</p> </body> </html> """ message = MIMEText(html_body, "html") message["Subject"] = "HTML Email Test" message["From"] = EMAIL message["To"] = recipient


Sending Emails with Attachments

To send emails with attachments, you need to use the MIMEMultipart class.

Example: Email with Attachment


import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders # Email configuration SMTP_SERVER = "smtp.gmail.com" SMTP_PORT = 587 EMAIL = "your_email@gmail.com" PASSWORD = "your_password" # Create the email subject = "Email with Attachment" body = "This email contains an attachment." message = MIMEMultipart() message["Subject"] = subject message["From"] = EMAIL message["To"] = recipient # Attach the email body message.attach(MIMEText(body, "plain")) # Attach a file filename = "example.txt" # File to attach with open(filename, "rb") as attachment: part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read()) # Encode the file in base64 encoders.encode_base64(part) part.add_header( "Content-Disposition", f"attachment; filename={filename}" ) message.attach(part) # Send the email try: with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server: server.starttls() server.login(EMAIL, PASSWORD) server.send_message(message) print("Email with attachment sent successfully!") except Exception as e: print(f"Error: {e}")

Common SMTP Server Settings

Provider SMTP Server Port (TLS) Port (SSL)
Gmail smtp.gmail.com 587 465
Yahoo Mail smtp.mail.yahoo.com 587 465
Outlook smtp.office365.com 587


Security Considerations

  1. App-Specific Passwords: For Gmail and some other providers, use an app-specific password instead of your main password.

  2. Environment Variables: Store sensitive information like email credentials in environment variables or configuration files instead of hardcoding them.

  3. OAuth2 Authentication: For enhanced security, consider using OAuth2 for authenticating with email providers.

Leave a Reply