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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例