Skip to content

Instantly share code, notes, and snippets.

@dldinternet
Forked from jamescalam/notify_message.py
Created May 18, 2020 16:15
Show Gist options
  • Save dldinternet/0ae400be1a9a13e39bf00f133a302253 to your computer and use it in GitHub Desktop.
Save dldinternet/0ae400be1a9a13e39bf00f133a302253 to your computer and use it in GitHub Desktop.
Example of using Python's email module to build an email message object containing a subject, body, attachments, and images.
import os
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
def message(subject="Python Notification", text="", img=None, attachment=None):
# build message contents
msg = MIMEMultipart()
msg['Subject'] = subject # add in the subject
msg.attach(MIMEText(text)) # add text contents
# check if we have anything given in the img parameter
if img is not None:
# if we do, we want to iterate through the images, so let's check that
# what we have is actually a list
if type(img) is not list:
img = [img] # if it isn't a list, make it one
# now iterate through our list
for one_img in img:
img_data = open(one_img, 'rb').read() # read the image binary data
# attach the image data to MIMEMultipart using MIMEImage, we add
# the given filename use os.basename
msg.attach(MIMEImage(img_data, name=os.path.basename(one_img)))
# we do the same for attachments as we did for images
if attachment is not None:
if type(attachment) is not list:
attachment = [attachment] # if it isn't a list, make it one
with open(attachment, 'rb') as f:
# read in the attachment using MIMEApplication
file = MIMEApplication(
f.read(),
name=os.path.basename(attachment)
)
# here we edit the attached file metadata
file['Content-Disposition'] = f'attachment; filename="{os.path.basename(attachment)}"'
msg.attach(file) # finally, add the attachment to our message object
return msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment