1 min read

Python Email Handling (smtplib)

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.

Importing the Module

import smtplib

Sending a Simple Email

To send an email, you generally need to connect to an SMTP server (like Gmail, Outlook, etc.).

import smtplib

sender_email = "my@gmail.com"
receiver_email = "your@gmail.com"
password = "password"
message = """\
Subject: Hi there

This message is sent from Python."""

try:
    # Create a secure SSL context
    # Note: For Gmail, you might need an App Password
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
    print("Email sent successfully!")
except Exception as e:
    print(f"Something went wrong: {e}")
finally:
    server.quit()

Sending HTML Email

To send rich content like HTML, you should use the email package to construct the message.

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

message = MIMEMultipart("alternative")
message["Subject"] = "Multipart Test"
message["From"] = "sender@email.com"
message["To"] = "receiver@email.com"

html = """\
<html>
  <body>
    <p>Hi,<br>
       How are you?<br>
    </p>
  </body>
</html>
"""

part = MIMEText(html, "html")
message.attach(part)

# Send the message via SMTP as shown above using message.as_string()

programming/python/python