Python SMTP发送邮件
- SMTP(Simple Mail Transfer Protocol),简单的邮件传输协议。他是一组用于从源地址到目的地址传输邮件的规范,通过它来控制邮件的中转方式。SMTP协议属于 TCP/IP 协议簇,它帮组每台计算机再送中转信件时找到下一个目的地。SMTP服务器遵循 SMTP 协议的发送邮件服务器
开启SMTP
- 这里我们以QQ邮箱为例,我们在邮箱设置 – 账户中找到开启服务,然后点击开启STMP
- 然后设置一下客户端授权码
- 发短信开启
然后我们可以通过python实现邮件发送了,下面是一个简单的例子
#! /usr/bin/python3
# -*- coding: UTF-8 -*-
import smtplib
import time
from email.mime.text import MIMEText
from email.header import Header
class TestMail(object):
def __init__(self):
self.mail_host = "smtp.qq.com"
self.mail_user = "xxxxx@qq.com"
self.mail_pass = "" # 这里是QQ客户端授权密码
self.sender = 'xxxxx@163.com'
self.receivers = ''
def send_mail(self):
body = 'Dear all:\n接口自动化测试报告如下:\n 测试用例集合:{}\n 运行结果:{}'.format('xxxx', 'xxxx')
tm = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
message = MIMEText(body, 'plain', 'utf-8')
message['From'] = self.mail_user
message['To'] = self.receivers
subject = '接口自动化报告测试'
message['Subject'] = Header(subject + '_' + tm, 'utf-8')
try:
smtpObj = smtplib.SMTP()
smtpObj = smtplib.SMTP_SSL(self.mail_host, 465)
smtpObj.login(self.mail_user, self.mail_pass)
smtpObj.sendmail(self.sender, self.receivers, message.as_string())
print('send mail ok')
except smtplib.SMTPException:
print('send mail fail')
if __name__ == "__main__":
send = TestMail()
send.send_mail()
- 然后通常在项目中,我们都是把邮箱的发送者和接受者以及一些邮件信息,单独放在config.yaml或者config.ini文件中进行配置化,下面我们来看看如何读取文件配置
读取配置
#! /usr/bin/python3
# -*- coding: UTF-8 -*-
[mail]
#发送邮件信息
mail_host = smtp.qq.com
mail_user = xxx@qq.com
mail_pass = # 163客户端授权密码
sender = @qq.com
receivers =
- 读取配置
#! /usr/bin/python3
# -*- coding: UTF-8 -*-
import smtplib
import time
from pathlib import Path
from email.mime.text import MIMEText
from email.header import Header
from configparser import ConfigParser
class TestMail(object):
def __init__(self):
self.config = ConfigParser()
self.conf_path = str(Path('config.ini').absolute()) # 读取绝对路径
self.config.read(self.conf_path, encoding='utf-8')
def send_mail(self):
body = 'Dear all:\nDEMO 接口自动化测试报告:\n 测试用例集合:{}\n 运行结果:{}'.format('xxxx', 'xxxx')
tm = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
message = MIMEText(body, 'plain', 'utf-8')
message['From'] = self.config.get('mail', 'sender')
message['To'] = self.config.get('mail', 'receivers')
subject = '接口自动化测试报告'
message['Subject'] = Header(subject + '_' + tm, 'utf-8')
try:
smtpObj = smtplib.SMTP()
smtpObj = smtplib.SMTP_SSL(self.config.get('mail', 'mail_host'), 465)
smtpObj.login(self.config.get('mail', 'mail_user'), self.config.get('mail', 'mail_pass'))
smtpObj.sendmail(self.config.get('mail', 'sender'), self.config.get('mail', 'receivers'), message.as_string())
print('send mail ok')
except smtplib.SMTPException:
print('send mail fail')
if __name__ == "__main__":
send = TestMail()
send.send_mail()
发送邮件带附件
- 通常我们发邮件有时会需要发送附件,比如测试报告,贴代码
#! /usr/bin/python3
# -*- coding: UTF-8 -*-
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
def send_kindle():
mail_host = "smtp.qq.com"
mail_user = "@qq.com"
mail_pass = ""
sender = '@qq.com'
receivers = '@kindle.cn'
message = MIMEMultipart()
message['From'] = mail_user
message['To'] = receivers
subject = '{}'.format(filename)
message['Subject'] = Header(subject, 'utf-8')
message.attach(MIMEText('{}'.format(filename), 'plain', 'utf-8'))
att1 = MIMEText(open('/Users/Documents/book/{}'.format(filename), 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="book.mobi"'
message.attach(att1)
try:
smtpObj = smtplib.SMTP_SSL(mail_host, 465)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print("发送成功")
except smtplib.SMTPException:
print("Error: 发送失败")
if __name__ == '__main__':
filename = input("请输入您要发送的附件名称")
os.path.split(filename)
send_kindle()
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/100698.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...