Send email from Python using SMTP.

Send email from Python using SMTP.

Sending email from Python using SMTP can be very handy if you want to implement alerting or some type of notification service in your Python programs.

I use this method for sending notifications from some of my algo stock trading Python programs as well as a security camera program I wrote which notifies me if a human is present in the frame of my security cameras.

Watch the Video Here: https://youtu.be/ikhKsGwxVgk

The Code

import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
import os
import sys

email_server = 'smtp.zoho.com:587'

email_user = 'test@jimburnett.com'

email_password = '##########'

attachments = []

def main():
    add_attachment("image1.jpg")
    response = send_email("test@jimburnett.com","jim@jimburnett.com","Testing from Python","Hello everyone this is an email test!")
    print(response)


#####EMAIL CODE STARTS HERE#####


    
def add_attachment(file_path):
    if os.path.isfile(file_path) is True:
        attachments.append(file_path)
        
def send_email(from_address,to_address, subject, body):
    try:
        server = smtplib.SMTP(email_server)
        msg = MIMEMultipart()
        msg['From'] = from_address
        msg['To'] = to_address
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        msg.attach(MIMEText(body))
        
        for attachment in attachments:
            with open(attachment, "rb") as fil:
                part = MIMEApplication(
                    fil.read(),
                    Name=os.path.basename(attachment)
                )
            part['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(attachment)
            msg.attach(part)

        server_ret = server.connect(email_server)
        server.ehlo()
        server.starttls()
        server.login(email_user, email_password)
        server.sendmail(from_address, [to_address], msg.as_string())
        server.close()
        return server_ret
    except:
        e = sys.exc_info()
        print("error in send_email: %s" % str(e))
        return False



if __name__ == "__main__":
    main()

About the author

Jim Burnett is a senior software engineer specializing in C++ and Python application development on Linux and Unix like operating systems.