Sending Email

Python – Send Email with SMTP

A Python script to send mail via an SMTP server

import smtplib
from socket import gaierror
import sys

my_email = "[email protected]"
password = "Password123"

mail_server = "mail.server.net"

subject = "Hello"
body = "This is the body of my email"

try:
    with smtplib.SMTP(mail_server) as connection:
        # Enable SMTP security - TLS
        # Will not proceed if this doesn't work
        try:
            connection.starttls()
        except Exception as err:
            print(err)
            connection.close()
            sys.exit()

        # Log on to the mail server
        try:
            connection.login(user=my_email, password=password)
        except smtplib.SMTPAuthenticationError:
            print("Bad authentication details")
            print("Check your username and password")
            connection.close()
            sys.exit()
        except smtplib.SMTPServerDisconnected:
            print("Unexpectedly disconnected from the mail server")
            print("The server may be down or the password was wrong too often")
            connection.close()
            sys.exit()

        # Send an email
        try:
            connection.sendmail(
                from_addr=my_email,
                to_addrs="[email protected]",
                msg=f"Subject:{subject}\n\n{body}"
            )
        except smtplib.SMTPDataError as err:
            if 'SPAM' in err:
                print("Sorry, your message has been detected as SPAM")
            else:
                print(err)

except gaierror:
    print("Problem connecting to the mail server")
    print("Check the address is correct")
    print("Check that a firewall is not blocking the connection")
    sys.exit()
except TimeoutError:
    print("Connection timed out while connecting to the mail server")
    sys.exit()