python 发送邮件附件很慢_python发送邮件带附件

importargparseimportsmtplib, mimetypesfrom email.mime.application importMIMEApplicationfrom email.mime.multipart importMIMEMultipartfrom email.mime.text importMIMETextfrom email.mime.image importMIMEImagefrom email importutilsfrom email importencodersfrom email.header importHeaderimportos.pathimportdatetimeimporttimeimportsys#import plugs.FileHelper as fileHelper

defaultencoding= 'utf-8'

if sys.getdefaultencoding() !=defaultencoding:

reload(sys)

sys.setdefaultencoding(defaultencoding)classSendMail():

startDate= ''

def __init__(self, reportDate):

startDate=reportDateprint('初始化SendMail邮件,值为:' +startDate)def SendMethod(self, startDate=None):print('SendMethod方法传参的值为:' +startDate)#发送邮箱服务器

smtpserver = 'mail.qq.com'

#smtpserver = 'smtp.163.com' 用smtplib.SMTP_SSL(smtpserver, 25)

#发送邮箱用户名密码

user = 'test@qq.com'password= 'test2018'

#发送和接收邮箱

sender = 'test@qq.com'receives= ['test@qq.com', 'test2@qq.com'] # ccs = ['test@qq.com']#发送邮件主题和内容

subject = f'{startDate}_测试'content= f'

您好~

附件为{startDate}数据。

请查收。

谢谢~

'\

f'

From robot>'

#构造附件内容:定义附件,构造附件内容

_rarUrl =os.path.dirname(

os.path.dirname(os.path.abspath(__file__))) + "\\test.zip"

print('附件地址是abspath:' +_rarUrl)#_rarUrl2 = self.getsql(r"\test.rar")

#构建发送与接收信息]

recc = receives +ccs

msgRoot= MIMEMultipart() #发送附件的方法定义为一个变量

msgRoot.attach(MIMEText(content, 'html', 'UTF-8')) #发送附件的方法中嵌套发送正文的方法

msgRoot['subject'] =subject

msgRoot['From'] =sender

msgRoot['To'] = ','.join(receives)

msgRoot['Cc'] = ','.join(ccs)

send_file= open(_rarUrl, 'rb').read() #'rb'表示r读取,b表示二进制方式读取

att= MIMEText(send_file, 'base64', 'utf-8') #调用传送附件模块,传送附件 send_file

#att = MIMEApplication(send_file) #用MIMEApplication 就不能有 base64和utf-8

att["Content-Type"] = 'application/octet-stream'att["Content-Disposition"] = f'attachment; filename={startDate}月测试.zip'

#att.add_header('Content-Disposition', 'attachment', filename=f'{startDate}月测试.zip')

msgRoot.attach(att) #添加附件到正文中

print("Start 登录服务器.")#SSL协议端口号要使用25

smtp = smtplib.SMTP(smtpserver, 25) #_SSL

print("Start 向服务器标识用户身份.")#HELO 向服务器标识用户身份

smtp.helo(smtpserver)print("Start 服务器返回结果确认.")#服务器返回结果确认

smtp.ehlo(smtpserver)print("Start 登录邮箱服务器用户名和密码.")try:#登录邮箱服务器用户名和密码

smtp.login(user, password)print("Start send email...")

smtp.sendmail(sender, recc, msgRoot.as_string())

smtp.quit()print("Send End!")exceptsmtplib.SMTPException as e:print('error:',e) #打印错误

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值