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 相关文章推荐
wxpython 学习笔记 第一天
Feb 09 Python
Python深入学习之上下文管理器
Aug 31 Python
使用Python的urllib2模块处理url和图片的技巧两则
Feb 18 Python
Python实现的生成格雷码功能示例
Jan 24 Python
使用python 打开文件并做匹配处理的实例
Jan 02 Python
python遍历小写英文字母的方法
Jan 02 Python
Scrapy框架爬取西刺代理网免费高匿代理的实现代码
Feb 22 Python
numpy np.newaxis 的实用分享
Nov 30 Python
Numpy之reshape()使用详解
Dec 26 Python
两行代码解决Jupyter Notebook中文不能显示的问题
Apr 24 Python
pytorch 如何使用float64训练
May 24 Python
Python合并pdf文件的工具
Jul 01 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插入中文到sqlserver 2008里出现乱码的解决办法分享
2012/07/19 PHP
PHP中把有符号整型转换为无符号整型方法
2015/05/27 PHP
php探针不显示内存解决方法
2019/09/17 PHP
Laravel 微信小程序后端实现用户登录的示例代码
2019/11/26 PHP
Locate a File Using a File Open Dialog Box
2007/06/18 Javascript
JavaScript 三种创建对象的方法
2009/10/16 Javascript
javascript客户端解决方案 缓存提供程序
2010/07/14 Javascript
11个用于提高排版水平的基于jquery的文字效果插件
2012/09/14 Javascript
javascript将数组插入到另一个数组中的代码
2013/01/10 Javascript
js动态创建、删除表格示例代码
2013/08/07 Javascript
限制textbox或textarea输入字符长度的JS代码
2013/10/16 Javascript
JavaScript中的原型prototype完全解析
2016/05/10 Javascript
JavaScript中对JSON对象的基本操作示例
2016/05/21 Javascript
Bootstrap入门教程一Hello Bootstrap初识
2017/03/02 Javascript
微信小程序 开发MAP(地图)实例详解
2017/06/27 Javascript
ng-repeat指令在迭代对象时的去重方法
2018/10/02 Javascript
Vue框架下引入ActiveX控件的问题解决
2019/03/25 Javascript
laypage.js分页插件使用方法详解
2019/07/27 Javascript
vue循环数组改变点击文字的颜色
2019/10/14 Javascript
JS写滑稽笑脸运动效果
2020/05/28 Javascript
weui上传多图片,压缩,base64编码的示例代码
2020/06/22 Javascript
Python 过滤字符串的技巧,map与itertools.imap
2008/09/06 Python
python按行读取文件,去掉每行的换行符\n的实例
2018/04/19 Python
python print 按逗号或空格分隔的方法
2018/05/02 Python
python使用tornado实现登录和登出
2018/07/28 Python
python利用Tesseract识别验证码的方法示例
2019/01/21 Python
Django学习之文件上传与下载
2019/10/06 Python
python中的itertools的使用详解
2020/01/13 Python
python 制作网站筛选工具(附源码)
2021/01/21 Python
CSS3径向渐变之大鱼吃小鱼之孤单的大鱼
2016/04/26 HTML / CSS
css3实现背景模糊的三种方式(小结)
2020/05/15 HTML / CSS
跑步爱好者一站式服务网站:Jack Rabbit
2016/09/01 全球购物
会计专业大学生职业生涯规划范文
2014/01/11 职场文书
安全生产检讨书
2014/01/21 职场文书
运动会铅球比赛加油稿
2014/09/26 职场文书
预备党员群众路线教育实践活动思想汇报2014
2014/10/25 职场文书