Work Automation – email send out with Word/PDF attachments

Another one around the topic of automated email sending, we have previously covered sending emails via in-house mail servers, Gmail servers as well as Outlook servers. In this post we’ll run through the sending of emails with file attachments. This script caters for most file types i.e. Word documents, PDF’s as well as Excel spreadsheets.

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.base import MIMEBase
from email import encoders

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

    File = open('C:/Desktop/word.dox','rb')
    attachment = MIMEBase('application','octet-stream')
    attachment.set_payload((File).read())
    encoders.encode_base64(attachment)
    attachment.add_header('Content-Disposition',"attachment; filename=DocumentName.docx")
    msg.attach(attachment)

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

sendEmail(Email,Password,ToAddress)

Leave a Reply