Skip to content

Instantly share code, notes, and snippets.

@guangningyu
Created December 5, 2016 16:15
Show Gist options
  • Save guangningyu/8e1ff895f48e4cee90488c803501c15f to your computer and use it in GitHub Desktop.
Save guangningyu/8e1ff895f48e4cee90488c803501c15f to your computer and use it in GitHub Desktop.
Send email in HTML format with embedded attachments and images.
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This module is used to send emails in HTML format, with embedded attachments and images.
"""
__version__ = '0.2'
__date__ = '2016-04-25'
__author__ = 'Guangning Yu'
import os
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.MIMEImage import MIMEImage
from email import encoders
from optparse import OptionParser
def send_mail(mail_host='192.168.0.1', subject=None, sender='[email protected]', to=[], cc=[], bcc=[], content=None, attach=[], images=[]):
def split(text):
return text.strip().replace(' ','').replace(',',';').split(';')
def filter_valid(list):
list = [i for i in list if '@example.com' in i]
return list
def to_str(list):
return ';'.join(list)
def print_info():
print 'Subject: %s' % subject
if sender:
print 'From: %s' % sender
if to:
print 'To: %s' % to_str(to)
if cc:
print 'Cc: %s' % to_str(cc)
if bcc:
print 'Bcc: %s' % to_str(bcc)
if attachs:
print 'Attachments:'
for i in attachs:
print ' %s' % i
if images:
print 'Images:'
for i in images:
print ' %s' % i
# Deal with parameters
subject = subject
sender = sender
to = filter_valid(split(to) if to else [])
cc = filter_valid(split(cc) if cc else [])
bcc = filter_valid(split(bcc) if bcc else [])
content = content
attachs = [os.path.abspath(file) for file in split(attach)] if attach else []
images = [os.path.abspath(file) for file in split(images)] if images else []
# Compose the message
receivers = []
msg = MIMEMultipart('related')
if subject:
msg['Subject'] = subject
if sender:
msg['From'] = sender
if to:
msg['To'] = to_str(to)
receivers += to
if cc:
msg['Cc'] = to_str(cc)
receivers += cc
if bcc:
receivers += bcc
# 1.attach email body
body = MIMEMultipart('alternative')
if content:
with open(content, 'rb') as f:
content = f.read()
content = MIMEText(content, _subtype='html')
body.attach(content)
else:
content = MIMEText('')
body.attach(content)
msg.attach(body)
# 2.attach attachments
if attachs:
for f in attachs:
ctype, encoding = mimetypes.guess_type(f)
maintype = None
subtype = None
if ctype:
maintype, subtype = ctype.split('/', 1)
attach = MIMEBase(maintype, subtype)
with open(f, 'rb') as fp:
attach.set_payload(fp.read())
file_name = f.split('/')[-1]
encoders.encode_base64(attach)
attach.add_header('Content-Disposition','attachment', filename=file_name)
msg.attach(attach)
# 3.attach images (note: the "img src" should have been added in the body)
if images:
for i in images:
image_name = i.split('/')[-1]
with open(i, 'rb') as f:
image_content = f.read()
image = MIMEImage(image_content)
image.add_header('Content-ID', '<%s>' % image_name)
msg.attach(image)
# Send the email
if sender and receivers:
print_info()
s = smtplib.SMTP()
s.connect(mail_host)
s.sendmail(sender, receivers, msg.as_string())
s.close()
else:
raise Exception("请指定发件人和收件人")
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-s", dest="subject", default=None, help='e.g."Weekly Report"')
parser.add_option("-f", dest="sender", default='[email protected]', help='e.g."[email protected]"')
parser.add_option("-r", dest="to", default=None, help='e.g."[email protected];[email protected]"')
parser.add_option("-c", dest="cc", default=None, help='e.g."[email protected];[email protected]"')
parser.add_option("-v", dest="bcc", default=None, help='e.g."[email protected]"')
parser.add_option("-b", dest="content", default=None, help='e.g."result.html"')
parser.add_option("-a", dest="attach", default=None, help='e.g."result.csv;result.gz"')
parser.add_option("-i", dest="images", default=None, help='e.g."img1.jpg;img2.jpg"')
(options, args) = parser.parse_args()
send_mail(
subject = options.subject,
sender = options.sender,
to = options.to,
cc = options.cc,
bcc = options.bcc,
content = options.content,
attach = options.attach,
images = options.images
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment