Email python 2

From UVOO Tech Wiki
Jump to navigation Jump to search
import smtplib
from email.mime.text import MIMEText

SMTP_SERVER = 'localhost'  # SMTP server address (echo server running on localhost)
SMTP_PORT = 1025  # Port used by the SMTP server

FROM = 'sender@example.com'  # Sender's email address
TO = ['recipient@example.com']  # Recipient's email address(es)

# Create a MIMEText object with the email content
message = MIMEText('This is the email body.')

# Add sender and recipient email addresses to the MIMEText object
message['From'] = FROM
message['To'] = ', '.join(TO)
message['Subject'] = 'Subject of the email'

try:
    # Connect to the SMTP server
    server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

    # Send the email
    server.sendmail(FROM, TO, message.as_string())
    print("Email sent successfully!")

except Exception as e:
    print("Failed to send email:", e)

finally:
    # Check if server is defined before trying to quit it
    if 'server' in locals():
        server.quit()