iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python email模块的使用实例
  • 562
分享到

python email模块的使用实例

实例模块python 2023-01-31 06:01:00 562人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

在使用python过程中,需要用的email模块来进行邮件的发送和接收,包含自定义邮件的中文、主题、日期、附件等信息,以下是我使用email模块来发送一个测试报告相关信息的邮件的例子: #!/usr/bin/Python # -*- co

在使用python过程中,需要用的email模块来进行邮件的发送和接收,包含自定义邮件的中文、主题、日期、附件等信息,以下是我使用email模块来发送一个测试报告相关信息的邮件的例子:

#!/usr/bin/Python
# -*- coding: utf-8 -*-
'''
@author:freesigefei
Created on 2016年3月20日
Updated on 2016年5月4日
'''
#------------------------------------------------------------------------------------------------
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import os,time,re

def send_Test_email(mail_to):
    '''本模块实现获取最新的测试报告html文件,读取部分报告内容作为邮件正文,将报告作为附件,并发送到指定的邮箱,
        参数mail_to代表的是接收邮箱,例如:'xxx@126.com' '''
    
    #发送邮箱
    mail_from = 'yyy@sina.com'
    #发送邮件主题
    mail_subject = 'Automation Test Report'
    #发送邮箱服务器
    mail_smtpserver = 'smtp.sina.com'
    #发送邮箱用户/密码
    mail_username = 'yyy@sina.com'
    mail_passWord = 'yyyyyy'

    #定义邮件内容,中文需参数‘utf-8’,单字节字符不需要
    '''
    #发送文件形式的邮件
    msg = MIMEText('你好!','text','utf-8')
    '''
    '''
    #发送html形式以正常文本显示在邮件内容中的邮件
    msg = MIMEText('<html><h1>你好!</h1></html>','html','utf-8')
    '''
    '''
    #读取html文件内容并发送
    f=open(file_new,'rb')
    mail_body=f.read()
    f.close()
    print mail_body
    msg=MIMEText(mail_body,_subtype='html',_charset='utf-8')
    '''
    
    #创建一个带附件的邮件实例(内容)
    msg = MIMEMultipart()
    #找到report目录下最新生成的报告文件供后续使用
    result_dir = 'D:\\report'
    lists=os.listdir(result_dir)
    lists.sort(key=lambda fn: os.path.getmtime(result_dir+"\\"+fn) if not
               os.path.isdir(result_dir+"\\"+fn) else 0)
    print (u'The Latest Test Report is: '+lists[-1])
    file_new = os.path.join(result_dir,lists[-1])
    #读取最新的测试报告文件获取部分信息来定义邮件的内容
    Regex_Theme=re.compile(r'Automation Test Report')
    Regex_Content=re.compile(r'<strong>(.*:)</strong>(.*)<')
    Report_File=open(file_new,'r')
    Mail_Content=[]
    for line in Report_File.readlines():
        if '<title>Automation Test Report</title>' in line or "<p class='attribute'>" in line:
            i=Regex_Theme.findall(line)
            j=Regex_Content.findall(line)
            if i != []:
                Mail_Content.append(i)
            if j != []:
                Mail_Content.append(j)
    Report_File.close()
    #将读取到的测试报告的数据以html形式显示为邮件的中文
    msgTest=MIMEText('''<html><h1>Test completed,Test results are as follows:</h1></html>'''
                     '''<hr />'''
                     '''<p><strong>'''+Mail_Content[0][0]+'''</strong></p>'''
                     '''<p><strong>'''+Mail_Content[1][0][0]+'''</strong>'''+Mail_Content[1][0][1]+'''</p>'''
                     '''<p><strong>'''+Mail_Content[2][0][0]+'''</strong>'''+Mail_Content[2][0][1]+'''</p>'''
                     '''<p><strong>'''+Mail_Content[3][0][0]+'''</strong>'''+Mail_Content[3][0][1]+'''</p>'''
                     '''<hr />'''
                     '''<p>PS: Detailed test results please refer to the attachment</p>'''
                     ,'html','utf-8')
    msg.attach(msgTest)
    #定义邮件的附件
    att1 = MIMEText(open(file_new, 'rb').read(), 'base64', 'utf-8')
    att1["Content-Type"] = 'application/octet-stream'
    att1["Content-Disposition"] ='attachment; filename="Automation test report.html"'#这里的filename指的是附件的名称及类型
    msg.attach(att1)
    #将邮件的主题等相关信息添加到邮件实例
    msg['Subject'] = Header(mail_subject)
    msg['From'] = mail_from
    msg['To'] = mail_to
    msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z') 
    #创建发送服务器实例并将发送服务器添加到实例中
    smtp = smtplib.SMTP()
    smtp.connect(mail_smtpserver)
    '''
    #采用ssl加密传输
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    '''
    '''
    #打印交互的日志信息
    #smtp.set_debuglevel(1)
    '''
    #登录发送邮件服务器并进行邮件的发送
    smtp.login(mail_username, mail_password)
    smtp.sendmail(mail_from, mail_to, msg.as_string())
    print u'Test report sent successfully,Please Go to the following email to check the test report :%s' %mail_to
    smtp.quit()
    
#----------------------------------------------------------------------------------------------------
if __name__ == "__main__":
    send_Test_email('xxx@126.com')


当然,如果要使用email模块的其他功能,可以参考网上的以下7个列子:

一,文件形式的邮件

#!/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('</pre>
<h1>你好</h1>
<pre>','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.
<img alt="" src="cid:image1" />
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', '')
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('你好','text','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 = """\

 
Hi!

       How are you?

       Here is the <a href="http://www.python.org">link</a> you wanted.

 

""" 

# 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()


7、基于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('你好','text','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()




--结束END--

本文标题: python email模块的使用实例

本文链接: https://www.lsjlt.com/news/190171.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python email模块的使用实例
    在使用python过程中,需要用的email模块来进行邮件的发送和接收,包含自定义邮件的中文、主题、日期、附件等信息,以下是我使用email模块来发送一个测试报告相关信息的邮件的例子: #!/usr/bin/python # -*- co...
    99+
    2023-01-31
    实例 模块 python
  • python中如何使用email模块
    python中如何使用email模块,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。说明email模块支持发送的邮件内容包括纯文本、HTML内容、图片和附件。email模块有几种...
    99+
    2023-06-20
  • Python模块学习--email
    可以使用Python的email模块来实现带有附件的邮件的发送。 SMTP (Simple Mail Transfer Protocol)   邮件传送代理 (Mail Transfer Agent,MTA) 程序...
    99+
    2023-01-31
    模块 Python email
  • Python如何使用email、smtplib、poplib、imaplib模块收发邮件
    一封电子邮件的旅程是:Mail User Agent (MUA) refers to an email client or software used by a user to access their email account.。(即类...
    99+
    2023-05-17
    Python email smtplib
  • python的numpy模块使用实例分析
    今天小编给大家分享一下python的numpy模块使用实例分析的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。Numpy是Nu...
    99+
    2023-06-30
  • python requests模块的使用示例
    目录为什么使用requests:模拟get请求:模拟请求头部信息模拟post请求requests上传文件requests设置代理time模块设置请求超时retrying模块设置刷新c...
    99+
    2024-04-02
  • python中的 uuid 模块使用示例
    此模块提供不可变的 UUID 对象 (类 uuid) 和函数uuid1()、uuid3()、uuid4()、uuid5(), 用于生成在 RFC 4122 中指定版本1、3、4和5UUIDs 。如果你想要的只是一个唯一 的ID,你应该调用...
    99+
    2023-01-30
    示例 模块 python
  • Python网络编程之使用email、smtplib、poplib、imaplib模块收发邮件
    一封电子邮件的旅程是: MUA:Mail User Agent——邮件用户代理。(即类似Outlook的电子邮件软件)MTA:Mail Transfer Ag...
    99+
    2024-04-02
  • python使用xlrd模块读取excel的方法实例
    目录一、安装xlrd模块:二、常用方法:1、导入模块:2、打开文件:3、获取sheet:4、获取sheet的汇总数据:5、单元格批量读取:6、特定单元格读取:7、(0,0)转换A1:...
    99+
    2024-04-02
  • 使用Python模块:struct模块
    Python没有提供直接的将用户定义的数据类型和文件IO关联起来的功能,但是它提供了struct库(是一个内置库)——我们可以以二进制模式来写这些数据(有趣的是,它真的是设计来讲文本数据写为缓存的) 1)bytes、str...
    99+
    2023-01-31
    模块 Python struct
  • Python使用Paramiko模块实现
    paramiko是用python写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。利用该模块,可以方便的进行ssh连接和sftp协议进行sftp文件传输以及远程命令执行。 通过安装包安装: wget ...
    99+
    2023-01-31
    模块 Python Paramiko
  • Python中模块的使用--binascii模块用法
    目录binascii模块用法binascii模块和进制转换笔记 Python内置函数binascii模块用法 binascii模块用于在二进制和ASCII之间转换 >...
    99+
    2024-04-02
  • python argparse模块传参用法实例
    目录前言传入一个参数操作args字典传入多个参数改变数据类型位置参数可选参数默认值必需参数前言 argsparse是python的命令行解析的标准模块,内置于python,不需要安装...
    99+
    2024-04-02
  • python copy模块中的函数实例用法
    1、copy.copy()函数可用于复制列表或字典等可变值,复制后的列表和原列表是两个独立的列表。 import copy origin = [1,2,3] new = copy...
    99+
    2024-04-02
  • Python socket 模块的使用
    一、使用socket实现一对一的简单通信  socket就是一个开往网络应用必备的功能模块。通过这个模块我们可以自己写程序的server端和client端,可以自己定义server端对外提供服务器的ip地址和端口。学会使用这个模块的之后我们...
    99+
    2023-01-31
    模块 Python socket
  • python Crypto模块的使用
    前一个星期一直再弄爬取网易云音乐的评论,真是一波三折,网页又是动态js,普通的方法获取不了,还有它发送的参数也要经过加密才....这篇文章就是写一下Crypto模块的使用。 Crypto不是自带的模块,需要下载。http://www.vo...
    99+
    2023-01-31
    模块 python Crypto
  • python time模块的使用
    我们先导入必须用到的一个module>>> import time设置一个时间的格式,下面会用到>>>ISOTIMEFORMAT=’%Y-%m-%d %X’看一下当前的时间,和其他很多语言相似这是从epo...
    99+
    2023-01-31
    模块 python time
  • Python matplotlib的spines模块实例详解
    目录spines 模块详解Spine 类Spine 类的定义Spine 类参数创建 Spine 对象的实例创建直线型 Spine 并添加到 axesspine_type=&lsquo...
    99+
    2024-04-02
  • Python 操作Excel-openpyxl模块用法实例
    目录openpyxl 的用法实例1.1 Openpyxl 库的安装使用1.2 Excel 的新建、读取、保存1.2.1 新建保存工作簿(覆盖创建)1.2.2 读取保存工作簿1.2.3...
    99+
    2023-05-19
    Python Excel-openpyxl模块使用 Excel-openpyxl用法
  • python os模块和fnmatch模块的使用介绍
    目录一、先介绍一下os模块1、拆分路径的方法介绍2、构建文件路径的方法介绍3、获取文件属性的方法介绍4、判断文件的类型5、文件和目录操作6、修改文件属性和判断文件属性7、遍历目录树二...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作