似乎遵循gmail电子邮件模板有效:
* multipart/alternative - text/plain - multipart/related + text/html <img src="cid:msgid"/> + image/png Content-ID: <msgid>
基于
#!/usr/bin/env python3import htmlimport mimetypesfrom email.headerregistry import Addressfrom email.message import EmailMessagefrom email.utils import make_msgidfrom pathlib import Pathtitle = 'Picture report…'path = Path('TESTING.png')me = Address("Pepé Le Pew", *gmail_user.rsplit('@', 1))msg = EmailMessage()msg['Subject'] = 'Report…'msg['From'] = memsg['To'] = [me]msg.set_content('[image: {title}]'.format(title=title)) # text/plaincid = make_msgid()[1:-1] # strip <> msg.add_alternative( # text/html '<img src="cid:{cid}" alt="{alt}"/>' .format(cid=cid, alt=html.escape(title, quote=True)), subtype='html')maintype, subtype = mimetypes.guess_type(str(path))[0].split('/', 1)msg.get_payload()[1].add_related( # image/png path.read_bytes(), maintype, subtype, cid="<{cid}>".format(cid=cid))# save to disk a local copy of the messagePath('outgoing.msg').write_bytes(bytes(msg))msg通过gmail发送:
import smtplibimport sslwith smtplib.SMTP('smtp.gmail.com', timeout=10) as s: s.starttls(context=ssl.create_default_context()) s.login(gmail_user, gmail_password) s.send_message(msg)Python 2/3兼容版本
* multipart/related - multipart/alternative + text/plain + text/html <div dir="ltr"><img src="cid:ii_xyz" alt="..."><br></div> - image/jpeg Content-ID: <ii_xyz>
基于发送带有嵌入式图像和纯文本备用内容的HTML电子邮件:
#!/usr/bin/env python# -*- coding: utf-8 -*-import cgiimport uuidimport osfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.header import Headerimg = dict(title=u'Picture report…', path=u'TESTING.png', cid=str(uuid.uuid4()))msg = MIMEMultipart('related')msg['Subject'] = Header(u'Report…', 'utf-8')msg['From'] = gmail_usermsg['To'] = ", ".join([to])msg_alternative = MIMEMultipart('alternative')msg.attach(msg_alternative)msg_text = MIMEText(u'[image: {title}]'.format(**img), 'plain', 'utf-8')msg_alternative.attach(msg_text)msg_html = MIMEText(u'<div dir="ltr">' '<img src="cid:{cid}" alt="{alt}"><br></div>' .format(alt=cgi.escape(img['title'], quote=True), **img), 'html', 'utf-8')msg_alternative.attach(msg_html)with open(img['path'], 'rb') as file: msg_image = MIMEImage(file.read(), name=os.path.basename(img['path'])) msg.attach(msg_image)msg_image.add_header('Content-ID', '<{}>'.format(img['cid']))msg通过gmail发送:
import ssls = SMTP_SSL('smtp.gmail.com', timeout=10, ssl_kwargs=dict(cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_TLSv1, # http://curl.haxx.se/ca/cacert.pem ca_certs='cacert.pem')) s.set_debuglevel(0)try: s.login(gmail_user, gmail_pwd) s.sendmail(msg['From'], [to], msg.as_string())finally: s.quit()SMTP_SSL是可选的,您可以改用
starttls问题中的方法:
import smtplibimport socketimport sslimport sysclass SMTP_SSL(smtplib.SMTP_SSL): """Add support for additional ssl options.""" def __init__(self, host, port=0, **kwargs): self.ssl_kwargs = kwargs.pop('ssl_kwargs', {}) self.ssl_kwargs['keyfile'] = kwargs.pop('keyfile', None) self.ssl_kwargs['certfile'] = kwargs.pop('certfile', None) smtplib.SMTP_SSL.__init__(self, host, port, **kwargs) def _get_socket(self, host, port, timeout): if self.debuglevel > 0: print>>sys.stderr, 'connect:', (host, port) new_socket = socket.create_connection((host, port), timeout) new_socket = ssl.wrap_socket(new_socket, **self.ssl_kwargs) self.file = getattr(smtplib, 'SSLFakeFile', lambda x: None)(new_socket) return new_socket


