首页 / 邮件 / python发送邮件带附件
python发送邮件带附件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python发送邮件带附件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2637字,纯文字阅读大概需要4分钟。
内容图文
![python发送邮件带附件](/upload/InfoBanner/zyjiaocheng/633/774b9247a5214390b5c233c9e49844a2.jpg)
import argparse import smtplib, mimetypes from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from email import utils from email import encoders from email.header import Header import os.path import datetime import time import sys # import plugs.FileHelper as fileHelper defaultencoding = 'utf-8' if sys.getdefaultencoding() != defaultencoding: reload(sys) sys.setdefaultencoding(defaultencoding) class SendMail(): startDate = '' def __init__(self, reportDate): startDate = reportDate print('初始化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' <p> 您好~ </p> <p>附件为{startDate}数据。</p><p> 请查收。 </p><p>谢谢~</p>' f'<br/><br/><br/><br/><p>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!") except smtplib.SMTPException as e: print('error:',e) #打印错误
内容总结
以上是互联网集市为您收集整理的python发送邮件带附件全部内容,希望文章能够帮你解决python发送邮件带附件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。