Python smtplib发送邮件 包含文本、附件、图片
2016-04-13 20:11
971 查看
#!/usr/bin/env python #coding: utf-8 ''' FuncName: smtplib_email.py Desc: 使用smtplib发送邮件 Date: 2016-04-11 14:00 Author: johnny ''' import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email.utils import COMMASPACE,formatdate from email import encoders def send_email_text(sender,receiver,host,subject,text,filename): assert type(receiver) == list msg = MIMEMultipart() msg['From'] = sender msg['To'] = COMMASPACE.join(receiver) msg['Subject'] = subject msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(text)) #邮件正文内容 for file in filename: #邮件附件 att = MIMEBase('application', 'octet-stream') att.set_payload(open(file, 'rb').read()) encoders.encode_base64(att) if file.endswith('.html'): # 若不加限定,jpg、html等格式附件是bin格式的 att.add_header('Content-Disposition', 'attachment; filename="今日测试结果.html"') # 强制命名,名称未成功格式化,如果可以解决请联系我 elif file.endswith('.jpg') or file.endswith('.png') : att.add_header('Content-Disposition', 'attachment; filename="pic.jpg"') else: att.add_header('Content-Disposition', 'attachment; filename="%s"' % file) msg.attach(att) smtp = smtplib.SMTP(host) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(username,password) smtp.sendmail(sender,receiver, msg.as_string()) smtp.close() if __name__=="__main__": sender = 'qqq@163.com' receiver = ['www@qq.com'] subject = "测试" text = "johnny'lab test" filename = [u'测试报告.html','123.txt',u'获取的信息.jpg'] host = 'smtp.163.com' username = 'qqq@163.com' password = 'qqq' send_email_text(sender,receiver,host,subject,text,filename)
已测试通过,使用Header并没有变成“头”,故未使用
若能解决附件格式为(html、jpg、png)在邮箱附件中格式不为“bin”的请联系我,希望此对大家有所帮助,谢谢
Python 邮件smtplib发送示例 请点击我传送
相关文章推荐
- python2.7升python3.2
- Python decorator 1: 函数
- python的基本输入输出
- Python 2.7 解决写入文件的中文乱码问题
- python安装
- 如何在Python中使用静态变量在计数
- 使用Selenium+firefox抓取网页指定firefox_profile后的问题
- Python虚拟环境安装virtualenv
- python3 字符串与列表常用功能
- python 转 exe -- py2exe库实录
- python笔记 - 高级属性(20160413)
- python 列表、字典的方法
- 用python导入mysql
- 解决Python UnicodeDecodeError: ‘ascii’ codec can’t decode
- Python3.5入门学习记录-函数
- Python -- 字符串大小写转换
- python 基础学习(字典对象,set对象)
- 初学python(对比java语言不同) 第九篇
- python 基础学习(元组,if,for)
- hive+python数据分析入门