Skip to content

Instantly share code, notes, and snippets.

@tklee1975
Created September 28, 2015 15:48
Show Gist options
  • Select an option

  • Save tklee1975/fece32e577a5bef9897b to your computer and use it in GitHub Desktop.

Select an option

Save tklee1975/fece32e577a5bef9897b to your computer and use it in GitHub Desktop.
Sending email with embed images using python
#!/usr/bin/python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
gmail_user = "test.address@gmail.com"
gmail_pwd = "password"
# Method
def send_email(msg, gmail_user, gmail_pwd, to_list):
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to_list, msg)
mailServer.quit()
# MAIN
to_list = ["address@gmail.com", "address@yahoo.com"]
# Create message container.
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = "Testing Subject"
msgRoot['From'] = "Testing"
msgRoot['To'] = ", ".join(to_list)
html = """\
<p>Testing <b>HTML</b></p>
<img width=100% src="cid:image1">
"""
msgHtml = MIMEText(html, 'html')
msgRoot.attach(msgHtml)
# Images
imagefile = "attach.png"
img = open(imagefile, 'rb').read()
msgImg = MIMEImage(img, 'png')
msgImg.add_header('Content-ID', '<image1>')
msgImg.add_header('Content-Disposition', 'inline', filename=imagefile)
msgRoot.attach(msgImg)
send_email(msgRoot.as_string(), gmail_user, gmail_pwd, to_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment