Work Automation – email send out with image attachments

The topic of automated emails seems to be a popular one, we have previously covered sending emails via in-house mail servers, Gmail servers as well as Outlook servers. In this post we will be going through how to add images as attachments to these automated emails.

Find the full source code for this project below, note that you can amend this very easily if you find yourself using an alternative server.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

def sendEmail(Email,Password,ToAddress):
    msg = MIMEMultipart() 
    body = ('Hello, This is a test email')
    msg.attach(MIMEText(body,'plain'))
    msg['Subject'] = "Some subject"
    msg['from'] = Email
    msg['To'] = ToAddress

    attachment = MIMEImage(open('C:/ImageSomewhere.png', 'rb').read())
    attachment.add_header('Content-ID', '<Image>')
    msg.attach(attachment)

    server = smtplib.SMTP('smtp-mail.outlook.com', 587) #Outlook
    #server = smtplib.SMTP('smtp.gmail.com:587') Gmail
    server.starttls()
    server.ehlo()
    server.login(Email,Password)
    server.sendmail(Email, ToAddress, msg.as_string())
    server.quit()


sendEmail(Email,Password,ToAddress)

Leave a Reply