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调用C/C++动态链接库的方法详解
Jul 22 Python
使用Python脚本将Bing的每日图片作为桌面的教程
May 04 Python
Python运行报错UnicodeDecodeError的解决方法
Jun 07 Python
python 文件转成16进制数组的实例
Jul 09 Python
浅析python3字符串格式化format()函数的简单用法
Dec 07 Python
Python中zip()函数的简单用法举例
Sep 02 Python
Python解释器以及PyCharm的安装教程图文详解
Feb 26 Python
如何利用Python识别图片中的文字
May 31 Python
keras 自定义loss model.add_loss的使用详解
Jun 22 Python
.img/.hdr格式转.nii格式的操作
Jul 01 Python
Python+Kepler.gl实现时间轮播地图过程解析
Jul 20 Python
python实现经纬度采样的示例代码
Dec 10 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 数组的指针操作实现代码
2011/02/08 PHP
标准版Eclipse搭建PHP环境的详细步骤
2015/11/18 PHP
一个简单安全的PHP验证码类、PHP验证码
2016/09/24 PHP
PHP针对中英文混合字符串长度判断及截取方法示例
2017/03/31 PHP
laravel model 两表联查示例
2019/10/24 PHP
使用javascipt---实现二分查找法
2013/04/10 Javascript
javascript中全局对象的isNaN()方法使用介绍
2013/12/19 Javascript
页面按钮禁用与解除禁用的方法
2014/02/19 Javascript
JavaScript中的toDateString()方法使用详解
2015/06/12 Javascript
jquery实现Ctrl+Enter提交表单的方法
2015/07/21 Javascript
14款经典网页图片和文字特效的jQuery插件-前端开发必备
2015/08/25 Javascript
js代码实现下拉菜单【推荐】
2016/12/15 Javascript
Vue如何实现组件的源码解析
2017/06/08 Javascript
基于vue cli 通过命令行传参实现多环境配置
2018/07/12 Javascript
Node.js 使用axios读写influxDB的方法示例
2018/10/26 Javascript
[46:53]Secret vs Liquid 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
python局部赋值的规则
2013/03/07 Python
Python实现类似jQuery使用中的链式调用的示例
2016/06/16 Python
Numpy中stack(),hstack(),vstack()函数用法介绍及实例
2018/01/09 Python
浅谈spring boot 集成 log4j 解决与logback冲突的问题
2020/02/20 Python
python 计算概率密度、累计分布、逆函数的例子
2020/02/25 Python
基于SQLAlchemy实现操作MySQL并执行原生sql语句
2020/06/10 Python
详解Python3 定义一个跨越多行的字符串的多种方法
2020/09/06 Python
Python 列表推导式需要注意的地方
2020/10/23 Python
Python析构函数__del__定义原理解析
2020/11/20 Python
python3.7中安装paddleocr及paddlepaddle包的多种方法
2020/11/27 Python
python爬虫利用selenium实现自动翻页爬取某鱼数据的思路详解
2020/12/22 Python
解决H5的a标签的download属性下载service上的文件出现跨域问题
2019/07/16 HTML / CSS
九年级化学教学反思
2014/01/28 职场文书
中秋节礼品促销方案
2014/02/02 职场文书
策划总监岗位职责
2014/02/16 职场文书
亮化工程实施方案
2014/03/17 职场文书
会议欢迎标语
2014/06/30 职场文书
家长给老师的感谢信
2015/01/20 职场文书
物资采购管理制度
2015/08/06 职场文书
MySQL Server 层四个日志
2022/03/31 MySQL