返回目录:电脑怎么了
6.1 SMTP发送邮件
SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
Python创建 SMTP 对象语法如下:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
参数说明:
1. host: SMTP 服务器主机。 你可以指定主机的ip地址或者域名如:runoob.com,这个是可选参数。
2. port: 如果你提供了 host 参数, 你需要指定 SMTP 服务使用的端口号,一般情况下SMTP端口号为25。
3. local_hostname: 如果SMTP在你的本机上,你只需要指定服务器地址为 localhost 即可。
Python SMTP对象使用sendmail方法发送邮件,语法如下:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
参数说明:
1. from_addr: 邮件发送者地址。
2. to_addrs: 字符串列表,邮件发送地址。
3. msg: 发送消息
注意:一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。
6.1.1 邮件发送综合案例(支持附件/群发)
例子:
import smtplib
import email.mime.multipart
import email.mime.text
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def send_email(smtpHost, sendAddr, password, recipientAddrs, subject='', content=''):
msg = email.mime.multipart.MIMEMultipart() #定义内嵌资源的邮件体
msg['from'] = sendAddr
receivers = recipientAddrs #收件人邮箱
msg['subject'] = subject
content = content
if len(receivers)>1:
msg['To'] = ','.join(receivers) #群发邮件
else:
msg['To'] = receivers[0]
txt = MIMEText(content, 'plain', 'utf-8')
msg.attach(txt)
# 添加附件,传送 result.html 文件
path = 'D:python_selenium3reportresult.html' # 附件路径
filename = path.split("")[-1] #提取附件文件名
part = MIMEApplication(open(path,'rb').read()) #读取文件
part.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(part)
smtp = smtplib.SMTP()
smtp.connect(smtpHost, '25') # 发件人邮箱中的SMTP服务器,端口是25,也可以是 465
smtp.login(sendAddr, password) #登录邮箱
smtp.sendmail(sendAddr, recipientAddrs, msg.as_string()) #发送邮件
print("发送成功!")
smtp.quit() # 退出邮箱
# 邮件信息
smtpHost = 'smtp.163.com' # 邮箱服务器地址
sender = '55666727@163.com' # 发送方邮箱
passwd = 'xny8816056' #填入发送方密码
receivers = ["xny_131421@163.com","xiaonengyou@126.com"] #收件人邮箱
subject = '华夏恒邦测试报告' #邮件标题
#邮件内容
content = """各位亲,
以下附件是华夏恒邦自动化测试报告,请查收!
请开发人员及时修复BUG!
"""
try:
send_email(smtpHost,sender, passwd, receivers, subject, content) # 调用send_email()方法发送邮件
except Exception as err:
print("发送失败!")
6.1.2 邮件发送方法的封装、数据分离与调用
为了实际项目的需求,把上面的邮件发送代码进行了优化,把代码拆分成3个文件,如下:
【m_methon】:封装成一个发送邮件方法。
import time,os
import email.mime.multipart
import email.mime.text
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import smtplib
from Mail_module.Mail_data import Mail_data
#from Mail_module.Mail_information import email_MIMEMultipart
class email_methon(Mail_data):
def Send_email(subject, content, filepath, receivers):
sender =Mail_data.sender # 发送方邮箱
passwd = Mail_data.passwd # 填入发送方密码
smtpHost =Mail_data.smtpHost #邮件服务器地址
receivers = receivers # 收件人邮箱
filepath =Mail_data.filepath
msgRoot = MIMEMultipart() # 定义内嵌资源的邮件体
msgRoot['Subject'] = subject
msgRoot['From'] = sender
if len(receivers) > 1:
msgRoot['To'] = ','.join(receivers) # 群发邮件
else:
msgRoot['To'] = receivers[0]
part = MIMEText(content)
msgRoot.attach(part)
# 添加附件,传送 result.html 文件
part = MIMEApplication(open(filepath, 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename="result.html")
msgRoot.attach(part)
try:
s = smtplib.SMTP() # 加载邮件模块的方法
s.connect(smtpHost) # 连接邮件服务器,我使用163邮箱:smtp.163.com,也可以使用其他的(比如:smtp.qq.com)
s.login(sender, passwd) # 登录邮箱
s.sendmail(sender, receivers, msgRoot.as_string()) # 发送邮件
print("邮件发送成功")
except smtplib.SMTPException as e:
print("Error, 发送失败")
finally:
s.quit()
【Mail_data】:存放发送邮件的数据。
class Mail_data():
smtpHost = 'smtp.163.com' # 邮箱服务器地址
sender = '55666727@163.com' # 发送方邮箱
passwd = 'xny8816056' #填入发送方密码
receivers = ["xny_131421@163.com","xiaonengyou@126.com"] #收件人邮箱
subject = '华夏恒邦测试报告' #邮件标题
content = """各位亲,
以下附件是华夏恒邦测试报告,请查收!
请开发人员及时修复BUG!
"""
filepath ='D:python_selenium3reportresult.html' # 附件路径
【mail】:发邮件
from Mail_module.m_methon import email_methon
from Mail_module.Mail_data import Mail_data
class mail(email_methon,Mail_data):
print("开始发送邮件...")
subject =Mail_data.subject # 邮件标题
#print(subject)
content =Mail_data.content # 邮件内容
receivers =Mail_data.receivers # 收件人邮箱
filepath =Mail_data.filepath
try:
email_methon.Send_email(subject, content, filepath, receivers) # 调用send_email()方法发送邮件
except Exception as err:
print("发送失败!")