Send email with Python

By , last updated July 9, 2019

Sending emails with Python scripts is easy if you have a server running. There are several libraries you need to use.

Start by importing smtplib and all the email modules in order to be able to send the emails.

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from time import sleep

The function to send the email should include type of message, title or subject of the message, to and from addresses, the body of the message in the form of the text and call the sending function sendmail.

def sendEmail(to, me, title, body):
        msg = MIMEMultipart('alternative')
        msg['Subject'] = title
        msg['From'] = me
        msg['To'] = to
        part2 = MIMEText(body, "html")
        msg.attach(part2)
        s = smtplib.SMTP('localhost')
        s.sendmail(me, [to], msg.as_string())
        s.quit()

Next create a body of the message, a subject and send.

body = "some text"
subject = "The subject"
sendEmail("email@mydomain.com", " email@mydomain.com", subject, body)

The body of the message may be anything, for example the result of parsing log files or you may open a text file and read the message from it:

fp = open(textfile, 'rb')
body = MIMEText(fp.read())
fp.close()