Jul
07
2022
python smtplib 发送邮件
#!/usr/bin/python # -*- coding: UTF-8 -*- # @author: jueyuanti327 import traceback,sys,os,smtplib,logging,base64,time # 加载smtplib模块 from email.mime.text import MIMEText from email.header import Header from email.utils import formataddr from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from email.utils import COMMASPACE, formatdate # sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') mail_Host = '172.17.0.7' # 发送者 sender = ("测试","xxxx@xxxx.xxx") # 这里的密码不是QQ邮箱的密码,而是在设置里开启SMTP服务器后的授权码 passwd = "smtp授权字符串" # 接受者 receivers = ['xm332719434@vip.qq.com'] # 邮件主题 subject = "Python 邮件发送测试..." # 邮件文本 mail_body = """ <p>Python 邮件发送测试...</p> <p><a href="{{url}}">{{url}}</a></p> """ file_list=['./优惠购机申请入口.url','./员工购5G手机终端.xlsx'] try: print(receivers) print(len(receivers)) # 连接邮件服务器 smtp = smtplib.SMTP(mail_Host) # smtp = smtplib.SMTP(mail_Host,1025) # smtp = smtplib.SMTP_SSL("smtp.qq.com", 465) # 发件人邮箱中的SMTP服务器,端口是25 # smtp.set_debuglevel(1) smtp.ehlo(mail_Host) # 登录到邮箱 如果自建smtp可以不用登录鉴权 # smtp.login(sender, passwd) i=1 files={} for receiver in receivers: url = 'http://xxx.xxx.xxx.xxx/alert/fish/?f={}'.format(receiver) try: # 创建一个带附件的实例 raw = MIMEMultipart() # 加入邮件标题 raw["Subject"] = Header(subject, 'utf-8') # 发件人格式 raw['From'] = formataddr((Header(sender[0], 'utf-8').encode(), sender[1])) # 收件人格式 raw['To'] = formataddr((Header(receiver.split('@')[0], 'utf-8').encode(), receiver)) raw.attach(MIMEText(mail_body.replace('{{url}}',url), 'html')) # 加入多个附件 for file_name in file_list: # 构造附件 filecontent = '' # 文件进行简单缓存减少IO读取 if not files.get(file_name): with open(file_name.encode(), 'rb') as f: files[file_name]=f.read() f.close() if os.path.splitext(file_name)[1] in ['.url']: filecontent = files[file_name].decode().replace('{{url}}',url).encode() else: filecontent = files[file_name] part = MIMEApplication(filecontent) # filename表示邮件中显示的附件名 part.add_header('Content-Disposition','attachment',filename = '%s' % os.path.basename(file_name)) raw.attach(part) smtp.sendmail(sender[1], receiver, raw.as_string()) time.sleep(0.5) logging.info("send success") print ('-----------------------\n\n') time.sleep(0.5) except Exception as e: logging.error("?邮件发送错误") print(e) print('traceback.format_exc():\n%s' % traceback.format_exc()) print("\n-------------\n({}/{}) is send\n-------------\n".format(i, len(receivers))) i+=1 smtp.quit() except Exception as e: print(e)
最活跃的读者