send an email in python

To send an email in Python, you need to use the smtplib and MIME modules. Here is a basic example of how to send an email using Gmail SMTP server:

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

# set up the SMTP server
smtp_server = "smtp.gmail.com"
smtp_port = 587 # for TLS
sender_email = "sender@gmail.com"
sender_password = "password"
receiver_email = "receiver@gmail.com"

# create message object instance
message = MIMEMultipart()

# set message headers
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Test email from Python"

# add message body
message_body = "This is a test email sent from Python."
message.attach(MIMEText(message_body, "plain"))

# create SMTP session
with smtplib.SMTP(smtp_server, smtp_port) as session:
    # start TLS for security
    session.starttls()
    # login to the SMTP server
    session.login(sender_email, sender_password)
    # send the email message
    session.sendmail(sender_email, receiver_email, message.as_string())
908 chars
32 lines

Replace the values of smtp_server, smtp_port, sender_email, sender_password, and receiver_email with the appropriate values for your email account and recipient.

gistlibby LogSnag