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中用函数作为返回值和实现闭包的教程
Apr 27 Python
Python 中 Virtualenv 和 pip 的简单用法详解
Aug 18 Python
通过shell+python实现企业微信预警
Mar 07 Python
django admin后台添加导出excel功能示例代码
May 15 Python
Python pandas.DataFrame调整列顺序及修改index名的方法
Jun 21 Python
Django框架下静态模板的继承操作示例
Nov 08 Python
Python使用循环神经网络解决文本分类问题的方法详解
Jan 16 Python
Python关键字及可变参数*args,**kw原理解析
Apr 04 Python
在django中实现choices字段获取对应字段值
Jul 12 Python
Python 的 __str__ 和 __repr__ 方法对比
Sep 02 Python
Python必备技巧之函数的使用详解
Apr 04 Python
python三子棋游戏
May 04 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
phpexcel导出excel的颜色和网页中的颜色显示不一致
2012/12/11 PHP
PHP分页类集锦
2014/11/18 PHP
php微信支付接口开发程序
2016/08/02 PHP
laravel获取不到session的三种解决办法【推荐】
2018/09/16 PHP
菜单效果
2006/10/14 Javascript
JS判断是否为数字,是否为整数,是否为浮点数的代码
2010/04/24 Javascript
基于JQuery的Select选择框的华丽变身
2011/08/23 Javascript
jquerymobile checkbox及时刷新才能获取其准确值
2012/04/14 Javascript
jQuery操作checkbox选择(list/table)
2013/04/07 Javascript
使用jquery.qrcode生成彩色二维码实例
2014/08/08 Javascript
Javascript中判断对象是否为空
2015/06/10 Javascript
javascript生成大小写字母
2015/07/03 Javascript
谈谈Jquery ajax中success和complete有哪些不同点
2015/11/20 Javascript
浅析JavaScript Array和string的转换(推荐)
2016/05/20 Javascript
深入理解Webpack 中路径的配置
2017/06/17 Javascript
使用原生js封装的ajax实例(兼容jsonp)
2017/10/12 Javascript
JS 实现百度搜索功能
2018/02/01 Javascript
Vue.js + Nuxt.js 项目中使用 Vee-validate 表单校验
2019/04/22 Javascript
vue项目首屏加载时间优化实战
2019/04/23 Javascript
原生JavaScript实现的无缝滚动功能详解
2020/01/17 Javascript
Nuxt的路由配置和参数传递方式
2020/11/06 Javascript
详解如何使用Python编写vim插件
2017/11/28 Python
Python中对象的引用与复制代码示例
2017/12/04 Python
对django中foreignkey的简单使用详解
2019/07/28 Python
Flask框架实现的前端RSA加密与后端Python解密功能详解
2019/08/13 Python
详解Python 中sys.stdin.readline()的用法
2019/09/12 Python
python 将视频 通过视频帧转换成时间实例
2020/04/23 Python
Python包资源下载路径报404解决方案
2020/11/05 Python
Python实现图片指定位置加图片水印(附Pyinstaller打包exe)
2021/03/04 Python
StubHub意大利:购买和出售全球演唱会和体育赛事门票
2017/11/21 全球购物
数控专业个人求职信范文
2014/02/05 职场文书
人事专员的职责
2014/02/26 职场文书
2015年幼儿园后勤工作总结
2015/04/25 职场文书
Go标准容器之Ring的使用说明
2021/05/05 Golang
微信小程序基础教程之echart的使用
2021/06/01 Javascript