Python邮件发送设置
1、自定义发送内容,发送给单个收件人
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tian'
__data__ = '2018/4/18 11:53'
import smtplib
from email.mime.text import MIMEText #MIMEText纯文本邮件模板
#发邮件相关的参数
smtpserver = "smtp.126.com" #发件服务器
port = 0 #端口
sender = "test_tx@126.com" # 账号
pwd = "xxxoooxxxoooxx" #发信密码一定要126开启smtp发给的密码,不是126登录的密码
receiver = '352932341@qq.com'#收件人列表
#编辑邮件内容
subject = "测试主题163" #自定义发送邮件主题
body = '<p>这是发送邮件的内容</p>' #自定义邮件正文,这里为html格式
msg = MIMEText(body,'html','utf-8')
msg['from'] = sender #发送者
msg['to'] = receiver #接收者
msg['subject'] = subject #主题
#发送邮件
try: #不用SSL认证
smtp = smtplib.SMTP()
smtp.connect(smtpserver)#连接服务器
smtp.login(sender,pwd) #登录
except:#需要SSL认证
smtp = smtplib.SMTP_SSL(smtpserver,port) #ssl认证,例如qq邮箱
smtp.login(sender,pwd) #登录
smtp.sendmail(sender,receiver,msg.as_string())#发送
smtp.quit() #关闭

2、发送带附件且发送给多人
需求:找到report目录下面最新的.html文件,然后调用本地搭建的邮件服务器发送给多人;
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tian'
__data__ = '2018/4/17 10:29'
import smtplib
from email_22.mime.text import MIMEText #纯文本邮件模板
from email_22.mime.multipart import MIMEMultipart #发送带附件
import os
def send_email(file_new):
#------------发件相关的参数------------------
smtpserver = "192.168.10.193" #发件服务器,本地搭建
port = 25 #端口
sender = "tianxiang@gz609.com" #账号
password = "xxxxxxooooo" #密码
receiver = ["352932341@qq.com","252xxxx000xx0@qq.com"]#多个收件人
#-------------编辑邮件内容--------------------
# 读文件
with open(file_new,"rb") as fr:
mail_body = fr.read()
msg = MIMEMultipart()
msg['From'] = sender #发件人
msg['To'] = ";".join(receiver) #收件人
msg['Subject'] = "appURL对比返回json结果" #主题
#正文
body = MIMEText(mail_body,"html","utf-8")
msg.attach(body)
#附件
att = MIMEText(mail_body,_subtype='html',_charset="utf-8")
att["Content-Type"] = "application/octet-stream"
att["Content-Disposition"] = 'attachment; filename="test_report.html"'
msg.attach(att)
#发送邮件
try:
smtp = smtplib.SMTP()
smtp.connect(smtpserver) #连接服务器
smtp.login(sender,password)#登录
except Exception as er:
smtp = smtplib.SMTP_SSL(smtpserver,port)
smtp.login(sender,password)#登录
smtp.sendmail(sender,receiver,msg.as_string())#发送
smtp.quit()#关闭
def send_report(testreport):
'''获取testreport目录下面最新的html文件'''
result_dir = testreport
lists = os.listdir(result_dir) #获取该目录下面的所有文件
#找到最新生成的文件
lists.sort(key=lambda fn:os.path.getmtime(result_dir+"\\"+fn))
#找到最新生成的文件
file_new = os.path.join(result_dir,lists[-1])
#调用发邮件模块
send_email(file_new)
def main_email():
'''需要发邮件文件中调用该方法'''
testreport = './report'
send_report(testreport)

浙公网安备 33010602011771号