How to send an email with Python

Sending emails with Python is a common task, especially for applications that require notifications, automatic reports, or confirmations. Thanks to the built-in smtplib module and additional libraries like email, this process can be easily automated.

Requirements

  • Python installed on your system
  • Access to an SMTP server (like Gmail, Outlook, or your company server)

Basic Code

Here is a basic example to send an email using Gmail as an SMTP server:

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

def send_email():
    # Email configuration
    sender = "youraddress@server.com"
    recipient = "recipient@example.com"
    password = "yourpassword"

    # Creating the message
    subject = "Email Subject"
    body = "This is the email content."

    msg = MIMEMultipart()
    msg["From"] = sender
    msg["To"] = recipient
    msg["Subject"] = subject
    msg.attach(MIMEText(body, "plain"))

    try:
        # Connecting to the SMTP server
        with smtplib.SMTP("smtp.server.com", 587) as server:
            server.starttls()
            server.login(sender, password)
            server.sendmail(sender, recipient, msg.as_string())
        print("Email sent successfully!")
    except Exception as e:
        print(f"Error sending email: {e}")

# Calling the function
send_email()

Details and Security

To protect your password, consider using environment variables or a separate configuration file. If you use Gmail, you may need to enable access for less secure apps or set up an app-specific password.

Extensions

To send more complex emails, such as those with attachments or HTML formatting, you can extend the code by adding appropriate MIME objects.

from email.mime.base import MIMEBase
from email import encoders

# Adding an attachment
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)

Conclusion

With these basics, you are ready to integrate email-sending functionality into your Python applications.

Back to top