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 相关文章推荐
精确查找PHP WEBSHELL木马的方法(1)
Apr 12 Python
Python ORM框架SQLAlchemy学习笔记之映射类使用实例和Session会话介绍
Jun 10 Python
Python中的hypot()方法使用简介
May 18 Python
Python实现身份证号码解析
Sep 01 Python
一文总结学习Python的14张思维导图
Oct 17 Python
python MNIST手写识别数据调用API的方法
Aug 08 Python
Centos7 下安装最新的python3.8
Oct 28 Python
python实现简单的购物程序代码实例
Mar 03 Python
使用 Python ssh 远程登陆服务器的最佳方案
Mar 06 Python
Python Selenium 设置元素等待的三种方式
Mar 18 Python
Windows下Sqlmap环境安装教程详解
Aug 04 Python
Python抓包并解析json爬虫的完整实例代码
Nov 03 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
业余方法DIY电子管FM收音机
2021/03/02 无线电
php去除html标记的原生函数详解
2015/01/27 PHP
php英文单词统计器
2016/06/23 PHP
PHP使用自定义方法实现数组合并示例
2016/07/07 PHP
PHP实现的字符串匹配算法示例【sunday算法】
2017/12/19 PHP
javascript 写类方式之五
2009/07/05 Javascript
asp.net下使用jquery 的ajax+WebService+json 实现无刷新取后台值的实现代码
2010/09/19 Javascript
非html5实现js版弹球游戏示例代码
2013/09/22 Javascript
Js中使用hasOwnProperty方法检索ajax响应对象的例子
2014/12/08 Javascript
Javascript实现禁止输入中文或英文的例子
2014/12/09 Javascript
深入理解JavaScript系列(17):面向对象编程之概论详细介绍
2015/03/04 Javascript
JavaScript返回当前会话cookie全部键值对照的方法
2015/04/03 Javascript
javascript实现Email邮件显示与删除功能
2015/11/21 Javascript
BootStrap下jQuery自动完成的样式调整
2016/05/30 Javascript
Js调用Java方法并互相传参的简单实例
2016/08/11 Javascript
bootstrap Table插件使用demo
2017/08/07 Javascript
详解vue挂载到dom上会发生什么
2019/01/20 Javascript
JavaScript实现的开关灯泡点击切换特效示例
2019/07/08 Javascript
Vue  webpack 项目自动打包压缩成zip文件的方法
2019/07/24 Javascript
vue实现点击追加选中样式效果
2019/11/01 Javascript
微信小程序scroll-view的滚动条设置实现
2020/03/02 Javascript
浅谈django三种缓存模式的使用及注意点
2018/09/30 Python
Python2和Python3.6环境解决共存问题
2018/11/09 Python
Python中如何使用if语句处理列表实例代码
2019/02/24 Python
Python+Selenium使用Page Object实现页面自动化测试
2019/07/14 Python
解决Pycharm的项目目录突然消失的问题
2020/01/20 Python
JAVA SWT事件四种写法实例解析
2020/06/05 Python
Python监听键盘和鼠标事件的示例代码
2020/11/18 Python
HTML5单页面手势滑屏切换原理
2016/03/21 HTML / CSS
英国版MAC彩妆品牌:Illamasqua
2018/04/18 全球购物
公务员年总结的自我评价
2013/10/25 职场文书
教师一帮一活动总结
2014/07/08 职场文书
小学班主任教育随笔
2015/08/15 职场文书
重阳节主题班会
2015/08/17 职场文书
MySQL命令行操作时的编码问题详解
2021/04/14 MySQL
MySQL的存储过程和相关函数
2022/04/26 MySQL