python - 发送邮件(smtplib、email)

发送邮件(smtplib、email)

通常在API和UI自动化测试后,都需要将运行的测试报告发送给指定邮件组接收,这个邮件发送功能可以利用python自带的两个模块完成:

  smtplib模块主要负责发送邮件如:连接邮箱服务器,登录邮箱,发送邮件

  email模块主要负责构造邮件如:发件人,收件人,主题,正文,附件、图片、HTML等

一、smtplib

 1、smtplib示例:

import smtplib
# 实例化SMTP连接(IP,端口)
smtp = smtplib.SMTP_SSL(self.SMTP_server, 465)  # 使用ssL安全加密方式连接邮箱服务器
# smtp.connect(self.SMTP_server, 465)           # 使用connect非安全方式连接邮箱服务器
#登录(邮箱账号、密码)
smtp.login(self.username, self.password)
#发送邮件(发件者邮件、收件者邮箱/多个收件者邮箱用逗号隔开,as_string()是将msg(MIMEText对象或者MIMEMultipart对象)变为str)
smtp.sendmail(self.sender, "[email protected]", msg.as_string())
#关闭SMTP连接
smtp.quit()

2、smtplib常用内置函数:

SMTP.set_debuglevel(level):#设置是否为调试模式。默认为False,

SMTP.connect([host[, port]]):#连接到指定的smtp服务器。参数分别表示smpt主机和端口。
# 默认是本机的25端口。也可以写成hostname:port的形式。

SMTP.docmd(cmd[, argstring]):#向smtp服务器发送指令。可选参数argstring表示指令的参数。

SMTP.helo([hostname]) :#使用"helo"指令向服务器确认身份。相当于告诉smtp服务器“我是谁”。

SMTP.has_extn(name):#判断指定名称在服务器邮件列表中是否存在。
 #出于安全考虑,smtp服务器往往屏蔽了该指令。

SMTP.verify(address) :#判断指定邮件地址是否在服务器中存在。
 #出于安全考虑,smtp服务器往往屏蔽了该指令。

SMTP.login(user, password) :#登陆到smtp服务器。

SMTP.sendmail(self, from_addr, to_addrs, msg, mail_options=[],
             rcpt_options=[]) :#发送邮件。

SMTP.quit() :#断开与smtp服务器的连接,相当于发送"quit"指令。

二、email

email模块下有mime包,mime英文全称为“Multipurpose Internet Mail Extensions”,即多用途互联网邮件扩展,是目前互联网电子邮件普遍遵循的邮件技术规范,mime包常用的内置方法如下:

  MIMEmultipart类型有三种:

MIMEMultipart(‘mixed‘) # 邮件类型为"multipart/mixed"的邮件包含附件。向上兼容,如果一个邮件有纯文本正文,超文本正文,内嵌资源,附件,则选择mixed类型。
MIMEMultipart(‘related‘) # 邮件类型为"multipart/related"的邮件正文中包括图片,声音等内嵌资源。
MIMEMultipart(‘alternative‘) # 邮件类型为"multipart/alternative"的邮件包括纯文本正文(text/plain)和超文本正文(text/html)。

  MIMEText:用于处理邮件中的HTML文本和text文本【纯文本正文(text/plain)和超文本正文(text/html)】;

  MIMEImage: 用于处理邮件中的图片图片

1、构建发件人、收件人、主题

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
msg = MIMEMultipart(‘mixed‘)
msg[‘Subject‘] = "邮件主题"
msg[‘From‘] = "发件人邮箱"
msg[‘To‘] = ‘收件人邮箱‘
msg[‘Date‘]=‘2012-3-16‘

注:

msg.add_header(_name,_value,**_params):添加邮件头字段。
msg.as_string():是将msg(MIMEText对象或者MIMEMultipart对象)变为str,如果只有一个html超文本正文或者plain普通文本正文的话,一般msg的类型可以是MIMEText;如果是多个的话,就都添加到MIMEMultipart,msg类型就变为MIMEMultipart。
msg.attach(MIMEText对象或MIMEImage对象):将MIMEText对象或MIMEImage对象添加到MIMEMultipart对象中。MIMEMultipart对象代表邮件本身,MIMEText对象或MIMEImage对象代表邮件正文,通俗的讲就是将文本,HTML,附件,图片都何以添加到MIMEMultipart(‘mixed‘)中。

2、构建文本内容

text = "test,test!!!"
text_plain = MIMEText(text,‘plain‘, ‘utf-8‘)
msg.attach(text_plain)    

3、构建HTML内容

html = """
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       test<br>
       Here is the <a href="http://www.baidu.com">link</a> you wanted.<br>
    </p>
  </body>
</html>
"""
text_html = MIMEText(html,‘html‘, ‘utf-8‘)
text_html["Content-Disposition"] = ‘attachment; filename="texthtml.html"‘
msg.attach(text_html)  

4、构建图片内容

sendimagefile=open(r‘E:\python\image.png‘,‘rb‘).read()
image = MIMEImage(sendimagefile)
image.add_header(‘Content-ID‘,‘<image1>‘)
image["Content-Disposition"] = ‘attachment; filename="testimage.png"‘
msg.attach(image)

5、构建附件内容

from email import encoders
sendfile=open(r‘D:\pythontest\report--201805171734.html‘,‘rb‘).read()
report = email.mime.text.MIMEText(sendfile,‘html‘, ‘utf-8‘)
report["Content-Type"] = ‘application/octet-stream‘
report.add_header(‘Content-Disposition‘, ‘attachment‘, filename=(‘gbk‘, ‘‘, report_name))
encoders.encode_base64(report) #将report进行base64编码处理
msg.attach(report)

三、完整示例

python 发送邮件,包含文本、HTML、图片、附件:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email import encoders

#设置smtplib所需的参数
#下面的发件人,收件人是用于邮件传输的。
smtpserver = ‘smtp服务器IP‘
username = ‘邮箱账号‘
password=‘邮箱密码‘
sender=‘发件者邮箱‘
#receiver=‘[email protected]‘
#收件人为多个收件人
receiver=[‘[email protected]‘,‘[email protected]‘]

#下面的主题,发件人,收件人,日期是显示在邮件页面上的。
msg = MIMEMultipart(‘mixed‘)
msg[‘Subject‘] = "邮件test"
msg[‘From‘] = ‘发件者邮箱‘
#msg[‘To‘] = ‘[email protected]‘
#收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
msg[‘To‘] = ";".join(receiver)
#msg[‘Date‘]=‘2012-3-16‘

#构造文字内容
text = "test,test!!!"
text_plain = MIMEText(text,‘plain‘, ‘utf-8‘)
msg.attach(text_plain)    

#构造图片链接
sendimagefile=open(‘E:\python\image.png‘,‘rb‘).read()
image = MIMEImage(sendimagefile)
image.add_header(‘Content-ID‘,‘<image1>‘)
image["Content-Disposition"] = ‘attachment; filename="testimage.png"‘
msg.attach(image)

#构造html
html = """
<html>
  <head></head>
  <body>
    <p>test!!!
    </p>
  </body>
</html>
"""
text_html = MIMEText(html,‘html‘, ‘utf-8‘)
text_html["Content-Disposition"] = ‘attachment; filename="texthtml.html"‘
msg.attach(text_html)

#构造附件
sendfile=open(‘D:\pythontest\report--201805171734.html‘,‘rb‘).read()
report = email.mime.text.MIMEText(sendfile, ‘html‘, ‘utf-8‘)
report["Content-Type"] = ‘application/octet-stream‘
report.add_header(‘Content-Disposition‘, ‘attachment‘, filename=(‘gbk‘, ‘‘, report_name))
encoders.encode_base64(report) #将report进行base64编码处理
msg.attach(report)

#发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtpserver,465)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

  

原文地址:https://www.cnblogs.com/Keep-Ambition/p/9090164.html

时间: 2024-08-29 06:47:42

python - 发送邮件(smtplib、email)的相关文章

Python发送邮件smtplib.SMTP各报错问题的解决方法

经测试可用的发送邮件代码: import smtplib from email.mime.text import MIMEText # 第三方 SMTP 服务 mail_host = "smtp.163.com" # SMTP服务器 mail_user = "username" # 用户名 mail_pass = "passwd" # 密码(这里的密码不是登录邮箱密码,而是授权码) sender = '[email protected]' # 发

Python发送邮件:smtplib、sendmail

本地Ubuntu 18.04,本地Python 3.6.5, 阿里云Ubuntu 16.04,阿里云Python 3.5.2, smtplib,sendmail 8.15.2, 今天,打算实现通过电子邮件发送 注册用户激活功能,原以为一天是够够的了,谁知,踩到 坑了:一个软件坑,一个ECS坑. 早上一来,便按照教程Python SMTP发送邮件做测试,很简单,使用smtplib模块 在 安装了sendmail的电脑上就可以执行邮件发送功能了. 只是,sendmail是什么?先用起来再说! 拷贝了

python爬虫-smtplib模块发送邮件

1.代码如下: import smtplib from email.message from EmailMessage # smtplib模块负责发送邮件服务 # email.message模块负责构建邮件,然后交给smtplib发送 # 定义SMTP服务器地址 smtp_server = 'smtp.163.com' # 定义发件人地址 from_addr = "***********@163.com" # 定义登录密码 password = '**********' # 定义收件人

【Python】 发邮件用 smtplib &amp; email

■ smtplib & email ■ 概述 发邮件主要用到smtplib以及email模块.stmplib用于邮箱和服务器间的连接,发送的步骤.email模块主要用于处理编码,邮件内容等等.主要是参考了那个发报表的脚本,简单记录了下最简单的用法,没啥参考价值= = ■ smtplib基本用法 smtp = smtplib.SMTP() #建立smtp对象 smtp.connect('server',port) #建立与smtp服务器的连接 smtp.login('user','password

python的邮件模块smtplib&email

import smtplib import string from email.mime.text import MIMEText def send_mail(host, sender, sender_passwd, receiver, content_file, port="25"):     # print "create smtp object"     server = smtplib.SMTP()     # print "conncect sm

python 发送邮件及smtplib.SMTPAuthenticationError 503 错误处理

发送失败错误1:smtplib.SMTPAuthenticationError:    我们使用python发送邮件时相当于自定义客户端根据用户名和密码登录,然后使用SMTP服务发送邮件,邮箱是默认不开启客户端授权的,因此登录总是被拒绝,解决办法(以qq邮箱为例):进入qq邮箱-设置-客户端授权密码-开启(授权码是用于登录第三方邮件客户端的专用密码),非第三方登录密码不变. 原文地址:https://www.cnblogs.com/sixing/p/8665286.html

python发送邮件方法总结

python中email模块使得处理邮件变得比较简单,今天着重学习了一下发送邮件的具体做法,这里写写自己的的心得,也请高手给些指点.     一.相关模块介绍 发送邮件主要用到了smtplib和email两个模块,这里首先就两个模块进行一下简单的介绍:    1.smtplib模块 smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])   SMTP类构造函数,表示与SMTP服务器之间的连接,通过这个连接可以向smtp服务器发送指令,执

【转载】python发送邮件实例

本文转自:http://www.cnblogs.com/lonelycatcher/archive/2012/02/09/2343463.html 这几天要用python发送邮件,上网找到这篇文章感觉蛮全面的,故转载收藏之. 1. 文件形式的邮件 #!/usr/bin/env python3 #coding: utf-8 import smtplib from email.mime.text import MIMEText from email.header import Header send

python发送邮件(一)

最近设计了一个小的应用程序,主要是根据文件中邮件地址发送一份excel中内容,并且在接受方收到邮件都是以网页的格式呈现的. 下面主要是对python发送邮件涉及到的部分知识点做个总结 一.先介绍一下Smtp协议和POP3协议 SMTP (Simple Mail Transfer Protocol) http://www.rfc-editor.org/info/rfc821    RFC821文档详细描述了这个协议信息: 邮件传送代理 (Mail Transfer Agent,MTA) 程序使用S