python发送邮件的实例代码(支持html、图片、附件)


Posted in Python onMarch 04, 2013

第一段代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib
def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText):
        strFrom = fromAdd
        strTo = ', '.join(toAdd)
        server = authInfo.get('server')
        user = authInfo.get('user')
        passwd = authInfo.get('password')
        if not (server and user and passwd) :
                print 'incomplete login info, exit now'
                return
        # 设定root信息
        msgRoot = MIMEMultipart('related')
        msgRoot['Subject'] = subject
        msgRoot['From'] = strFrom
        msgRoot['To'] = strTo
        msgRoot.preamble = 'This is a multi-part message in MIME format.'
        # Encapsulate the plain and HTML versions of the message body in an
        # 'alternative' part, so message agents can decide which they want to display.
        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative)
        #设定纯文本信息
        msgText = MIMEText(plainText, 'plain', 'utf-8')
        msgAlternative.attach(msgText)
        #设定HTML信息
        msgText = MIMEText(htmlText, 'html', 'utf-8')
        msgAlternative.attach(msgText)
       #设定内置图片信息
        fp = open('test.jpg', 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header('Content-ID', '<image1>')
        msgRoot.attach(msgImage)
       #发送邮件
        smtp = smtplib.SMTP()
       #设定调试级别,依情况而定
        smtp.set_debuglevel(1)
        smtp.connect(server)
        smtp.login(user, passwd)
        smtp.sendmail(strFrom, strTo, msgRoot.as_string())
        smtp.quit()
        return
if __name__ == '__main__' :
        authInfo = {}
        authInfo['server'] = 'smtp.somehost.com'
        authInfo['user'] = 'username'
        authInfo['password'] = 'password'
        fromAdd = 'username@somehost.com'
        toAdd = ['someone@somehost.com', 'other@somehost.com']
        subject = '邮件主题'
        plainText = '这里是普通文本'
        htmlText = '<B>HTML文本</B>'
        sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText)

文件形式的邮件

#!/usr/bin/env python3   
#coding: utf-8   
import smtplib   
from email.mime.text import MIMEText   
from email.header import Header   sender = '***'   
receiver = '***'   
subject = 'python email test'   
smtpserver = 'smtp.163.com'   
username = '***'   
password = '***'   
msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8',单字节字符不需要   
msg['Subject'] = Header(subject, 'utf-8')   
smtp = smtplib.SMTP()   
smtp.connect('smtp.163.com')   
smtp.login(username, password)   
smtp.sendmail(sender, receiver, msg.as_string())   
smtp.quit()  

HTML形式的邮件

#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.text import MIMEText
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'
msg = MIMEText('<html><h1>你好</h1></html>','html','utf-8')
msg['Subject'] = subject
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

带图片的HTML邮件

#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>good!','html','utf-8')
msgRoot.attach(msgText)
fp = open('h:\\python\\1.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msgRoot.as_string())
smtp.quit()

带附件的邮件

#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
#构造附件
att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="1.jpg"'
msgRoot.attach(att)
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msgRoot.as_string())
smtp.quit()

群邮件

#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.text import MIMEText
sender = '***'
receiver = ['***','****',……]
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'
msg = MIMEText('你好','plain','utf-8')
msg['Subject'] = subject
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

各种元素都包含的邮件

#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="http://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
#构造附件
att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="1.jpg"'
msg.attach(att)
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

基于SSL的邮件

#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'
msg = MIMEText('你好','plain','utf-8')#中文需参数‘utf-8',单字节字符不需要
msg['Subject'] = Header(subject, 'utf-8')
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.set_debuglevel(1)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
Python 相关文章推荐
Python+django实现文件下载
Jan 17 Python
Python序列操作之进阶篇
Dec 08 Python
Python实现霍夫圆和椭圆变换代码详解
Jan 12 Python
python中requests和https使用简单示例
Jan 18 Python
对django中render()与render_to_response()的区别详解
Oct 16 Python
python如何给字典的键对应的值为字典项的字典赋值
Jul 05 Python
python切片的步进、添加、连接简单操作示例
Jul 11 Python
提升Python效率之使用循环机制代替递归函数
Jul 23 Python
python tkinter基本属性详解
Sep 16 Python
Django之使用celery和NGINX生成静态页面实现性能优化
Oct 08 Python
Keras构建神经网络踩坑(解决model.predict预测值全为0.0的问题)
Jul 07 Python
如何用Python搭建gRPC服务
Jun 30 Python
python用ConfigObj读写配置文件的实现代码
Mar 04 #Python
Python编码时应该注意的几个情况
Mar 04 #Python
python中定义结构体的方法
Mar 04 #Python
Python语言技巧之三元运算符使用介绍
Mar 04 #Python
python解决字典中的值是列表问题的方法
Mar 04 #Python
python实现的各种排序算法代码
Mar 04 #Python
python 获取本机ip地址的两个方法
Feb 25 #Python
You might like
php获取mysql数据库中的所有表名的代码
2011/04/23 PHP
php设计模式 Command(命令模式)
2011/06/26 PHP
php防止sql注入之过滤分页参数实例
2014/11/03 PHP
laravel框架如何设置公共头和公共尾
2019/10/22 PHP
PHP配合fiddler抓包抓取微信指数小程序数据的实现方法分析
2020/01/02 PHP
HR vs ForZe BO3 第二场 2.13
2021/03/10 DOTA
javascript编程起步(第六课)
2007/02/27 Javascript
javascript setAttribute, getAttribute 在不同浏览器上的不同表现
2010/08/05 Javascript
40款非常棒的jQuery 插件和制作教程(系列二)
2011/11/02 Javascript
jquery创建一个ajax关键词数据搜索实现思路
2013/02/26 Javascript
js中return false(阻止)的用法
2013/08/14 Javascript
js 控制页面跳转的5种方法
2013/09/09 Javascript
onkeyup,onkeydown和onkeypress的区别介绍
2013/10/21 Javascript
JavaScript通过function定义对象并给对象添加toString()方法实例分析
2015/03/23 Javascript
javascript实现简单的贪吃蛇游戏
2015/03/31 Javascript
JS实现淘宝支付宝网站的控制台菜单效果
2015/09/28 Javascript
AngularJs  unit-testing(单元测试)详解
2016/09/02 Javascript
简单模拟node.js中require的加载机制
2016/10/27 Javascript
Angular异步变同步处理方法
2018/08/13 Javascript
优雅的elementUI table单元格可编辑实现方法详解
2018/12/23 Javascript
微信小程序实现上传多张图片、删除图片
2020/07/29 Javascript
让 python 命令行也可以自动补全
2014/11/30 Python
python3中的md5加密实例
2018/05/29 Python
Python并发:多线程与多进程的详解
2019/01/24 Python
python中append实例用法总结
2019/07/30 Python
利用Python脚本实现自动刷网课
2020/02/03 Python
python GUI库图形界面开发之PyQt5 UI主线程与耗时线程分离详细方法实例
2020/02/26 Python
Python restful框架接口开发实现
2020/04/13 Python
Django Channel实时推送与聊天的示例代码
2020/04/30 Python
解决Keras的自定义lambda层去reshape张量时model保存出错问题
2020/07/01 Python
用ldap作为django后端用户登录验证的实现
2020/12/07 Python
英国奢侈品网站:MatchesFashion
2016/12/16 全球购物
全球最大的在线橄榄球商店:Lovell Rugby
2018/05/20 全球购物
Hotels.com越南:酒店预订
2019/10/29 全球购物
护士自荐信怎么写
2013/10/18 职场文书
张丽莉事迹观后感
2015/06/16 职场文书