2 min read

Python Smtplib Module (Email)

The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. It is usually used in conjunction with the email module to construct messages.

Importing the Modules

import smtplib
import ssl
from email.message import EmailMessage

Basic Email Sending

To send an email, you typically need an SMTP server (like Gmail, Outlook, or a local server).

# Configuration
smtp_server = "smtp.gmail.com"
port = 465  # For SSL
sender_email = "my@gmail.com"
password = "my_app_password" # Use App Passwords, not login password
receiver_email = "receiver@example.com"

# Create the message
msg = EmailMessage()
msg.set_content("This is the body of the email.")
msg['Subject'] = "Test Email from Python"
msg['From'] = sender_email
msg['To'] = receiver_email

# Create a secure SSL context
context = ssl.create_default_context()

# Send the email
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.send_message(msg)

HTML Content

You can send HTML emails for better formatting.

msg = EmailMessage()
msg['Subject'] = "HTML Email"
msg['From'] = sender_email
msg['To'] = receiver_email

msg.set_content("This is the fallback text.")

html_content = """\
<html>
  <body>
    <h1>Hello!</h1>
    <p>This is an <b>HTML</b> email.</p>
  </body>
</html>
"""

msg.add_alternative(html_content, subtype='html')

Attachments

To send files, you need to read the file in binary mode and attach it to the message.

import mimetypes

filename = 'document.pdf'

with open(filename, 'rb') as f:
    file_data = f.read()
    file_name = f.name

    # Guess the MIME type or default to application/octet-stream
    maintype, subtype = mimetypes.guess_type(file_name)[0].split('/', 1)

    msg.add_attachment(file_data, maintype=maintype, subtype=subtype, filename=file_name)

programming/python/python