您的位置:首页 > 编程语言 > Python开发

python 发送邮件

2015-08-27 16:11 671 查看
前阵子改了下邮件系统一些BUG,顺便了解下python的邮件模块
#coding=utf8
import smtplib
import mimetypes
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

def SendMail():
msg = MIMEMultipart()
'''不使用Header转换邮件头部会乱码'''
msg['From'] = ("%s<%s>") % (Header('管理员','utf-8'),'mailfrom@163.com')
To = ["123456788@qq.com","123456789@qq.com"]
msg['To'] = ','.join(To)
msg['Subject'] = Header('附件邮件','utf-8')

#text: 文本邮件会与html邮件冲突,导致覆盖(二选一)
txt = MIMEText("啦啦啦德玛西亚",'plain','utf-8')
msg.attach(txt)

#html + 图片 html邮件会与文本邮件冲突(二选一)
'''html 也可单独发送html'''
content = '''<!DOCTYPE html><html><font size="5" color="red">红色的</font>
<p><font size="3" color="red">This is test Email ~_~!</font></p> <img src="cid:image1"></html>'''
html = MIMEText(content, 'html', 'utf-8')
msg.attach(html)
'''也可以不嵌入到上面的html中,单独以附件的方式发送图片'''
file1 = "2407531.jpg"
with open(file1,'rb') as f:
content = f.read()
image = MIMEImage(content)
image.add_header('Content-ID','<image1>')
msg.attach(image)

#附件
file2 = 'APScheduler-2.0.3.tar.gz'
with open(file2,'rb') as f:
content = f.read()
Attachments = MIMEText(content, 'base64', 'utf-8')
Attachments["Content-Type"] = 'application/octet-stream'
Attachments["Content-Disposition"] = 'attachment; filename="APScheduler-2.0.3.tar.gz"'
msg.attach(Attachments)

server = smtplib.SMTP()
#也可以在上一辈初始化的时候连接
server.connect('smtp.163.com')
server.login('xxx@163.com','password')
#msg['From']:可以为发件邮箱,也可为发件邮箱+别名
#To: 可以为字符串或列表,为字符串时默认为单个邮箱,群发时为列表
server.sendmail(msg['From'],To,msg.as_string())
print msg.as_string()
server.quit()

if __name__ == "__main__":
SendMail()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 邮件