python发送邮件
python发送html邮件的的API可以参考python官方文档,但是可能会出现邮件的样式不符合预期,例如样式不全,图片展示异常等。这里总结2个踩过的坑的经验:
- html要使用table的方式布局,不排除现在有些邮件客户端对div方式的布局支持也挺好的,对于布局比较简单的html邮件,一般table布局和div都可以,但是对于布局复杂的邮件,使用div不一定会有问题,但是有问题的几率就会增大,对于各式各样的邮件客户端,其兼容性也不如table布局好。
- 对于图片,使用html嵌入svg代码的方式,有些邮件客户端支持,有些支持的不好,因此最好的方式还是使用附件的方式。
一个简答的发送邮件的例子程序:
├── email_template.html
├── foot.jpg
├── head.jpg
└── send_email.py
email_template.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>告警邮件</title>
</head>
<body>
<table width="800px" cellpadding="0" cellspacing="0" align="center">
<tr>
<td><img src="cid:head_jpg" width="800px"/></td>
</tr>
<tr>
<table width="800px" cellpadding="0" cellspacing="0">
<tr>
<td width="100px"></td>
<td width="600px">
<table>
<tr>
<td>这是正文</td>
</tr>
<tr>
<td>这是正文</td>
</tr>
<tr>
<td>这是正文</td>
</tr>
<tr>
<td>这是正文</td>
</tr>
</table>
</td>
<td width="100px"></td>
</tr>
</table>
</tr>
<tr>
<td><img src="cid:foot_jpg" width="800px"/></td>
</tr>
</table>
</body>
</html>
send_mail.py
#!/usr/bin/env python
# coding=utf-8
"""
Send html email test
"""
import os
from email.header import Header
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
_EMAIL_TEMPLATE = 'email_template.html'
def _get_mime_image(image_path, cid):
with open(image_path, 'rb') as f:
msg_image = MIMEImage(f.read())
msg_image.add_header('Content-ID', '<%s>' % cid)
return msg_image
def _get_mime_text(html_content):
msg_alternative = MIMEMultipart('alternative')
msg_text = MIMEText(html_content, 'html', 'utf-8')
msg_alternative.attach(msg_text)
return msg_alternative
def _get_email_template():
cur_path = os.path.dirname(__file__)
email_template_path = os.path.join(cur_path, _EMAIL_TEMPLATE)
with open(email_template_path, 'r') as f:
content = f.read()
return content
def main():
email_server_host = 'smtp.163.com'
email_server_port = 465
username = 'user_sender@163.com'
password = 'password'
receivers = ['user_revicer@qq.com', username]
msg_root = MIMEMultipart('related')
msg_root['Subject'] = Header(u'发送邮件测试', 'utf-8')
msg_root['From'] = username
msg_root['To'] = '; '.join(receivers)
html_content = _get_email_template()
msg_root.attach(_get_mime_text(html_content))
cur_path = os.path.dirname(__file__)
head_jpg = os.path.join(cur_path, 'head.jpg')
msg_root.attach(_get_mime_image(head_jpg, 'head_jpg'))
foot_jpg = os.path.join(cur_path, 'foot.jpg')
msg_root.attach(_get_mime_image(foot_jpg, 'foot_jpg'))
client = smtplib.SMTP_SSL(email_server_host, email_server_port)
client.login(username, password)
client.sendmail(username, receivers, msg_root.as_string())
client.quit()
if __name__ == '__main__':
main()