python发送带图片内容的邮件
2020-05-05 本文已影响0人
LCSan
#!/usr/bin/python
#coding:utf-8
'''
Created on 2020年5月5日
@author: 瞌睡蟲子
'''
import smtplib
import mimetypes
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
import os
def sendMail(smtpHost="127.0.0.1",
mailName="",
mailPwd="",
sendTo=[],
cc=[],
bcc=[],
title="",
conetent="",
conetentImags=[],
attachments=[],
smtpPort=25,
ssl=False):
#创建一个带附件的实例
msg = MIMEMultipart('alternative')
msg['Subject'] = Header(title, 'utf-8')
msg['From'] = Header(mailName)
msg['To'] = Header(",".join(sendTo))
if len(cc)>0:
msg['Cc'] = Header(",".join(cc))
if len(bcc)>0:
msg['BCc'] = Header(",".join(bcc))
if len(conetentImags) > 0:
tmlist = tuple(
[v + str(k) for k, v in enumerate(["image"] * len(conetentImags))])
htm = MIMEText(conetent.format(*tmlist), 'html', 'utf-8')
else:
htm = MIMEText(conetent, 'html', 'utf-8')
msg.attach(htm)
for k, img in enumerate(conetentImags):
with open(img, 'rb') as fe:
image = MIMEImage(fe.read())
image.add_header('Content-ID', '<image' + str(k) + '>')
msg.attach(image)
for attch in attachments:
with open(attch, 'rb') as fe:
att = MIMEApplication(fe.read())
att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attch))
msg.attach(att)
if ssl:
with smtplib.SMTP_SSL(smtpHost, smtpPort) as s:
# 登录
s.login(mailName, mailPwd)
# 发送
s.sendmail(mailName, sendTo+cc+bcc, msg.as_string())
return True
else:
with smtplib.SMTP(smtpHost, smtpPort) as s:
# 登录
s.login(mailName, mailPwd)
# 发送
s.sendmail(mailName, sendTo+cc+bcc, msg.as_string())
return True
if __name__ == '__main__':
# 发送带图片内容的邮件(word转html格式,稍微处理直接发送)
sendMail(smtpHost="smtp.xxx.com",
mailName="xxx@xxx.com",
mailPwd="xxx",
sendTo=["xxx@qq.com"],
cc=["xxx@163.com"],
bcc=["xxx@qq.com"],
title="我是来测试的",
conetent='''
<html>
<head></head>
<body>
<p>
我是来测试的
<br><img src="cid:{}"></br>
</p>
</body>
</html>
''',
conetentImags=[r"C:\Users\Administrator\Desktop\QQ截图20200326122241.png"],
attachments=[r"C:\Users\Administrator\Desktop\邮箱专用.docx"],
smtpPort=25,
ssl=False)