1 # -*- coding: utf-8 -*- 2 # @Author : 107 3 # @File : emaildriver.py 4 # @explain : 发邮件 5 import json 6 import re 7 import smtplib 8 import email 9 import time 10 from email.mime.text import MIMEText 11 from email.utils import formataddr 12 from email.mime.multipart import MIMEMultipart 13 import imaplib 14 15 import os 16 17 18 class SendEmail: 19 def __init__(self, sender, sender_name, sender_token, attn, attn_name, subject, connect, files, server): 20 """ 21 :param sender: 发件人邮箱账号 22 :param sender_name: 发件人邮箱昵称 23 :param sender_token: 发件人邮箱密码(当时申请smtp给的口令) 24 :param attn: 收件人邮箱账号 25 :param attn_name: 收件人邮箱昵称 26 :param subject: 主题 27 :param connect: 内容 28 :param files: 附件,格式:{'path': '路径', 'read': 'r', 'encoding': 'utf-8', '_charset': 'utf-8', 'name': '文件名'} 29 :param server: 邮件服务器地址 30 """ 31 self.sender = sender 32 self.sender_name = sender_name 33 self.sender_token = sender_token 34 self.attn = attn 35 self.attn_name = attn_name 36 self.subject = subject 37 self.connect = connect 38 self.files = files 39 self.server = server 40 41 def accessory(self, file): 42 """ 43 处理单个附件 44 :param file: 45 :return: 46 """ 47 path = file.get('path') 48 rea = file.get('read') 49 e = file.get('encoding') 50 _charset = file.get('_charset') 51 name = file.get('name') 52 if not name: 53 name = os.path.split(path)[-1] 54 if e: 55 with open(path, rea, encoding=e) as r: 56 connect = r.read() 57 else: 58 with open(path, rea) as r: 59 connect = r.read() 60 acc = MIMEText(connect, _charset=_charset) 61 acc["Content-Type"] = 'application/octet-stream' 62 # 不能兼容outlook 63 # acc1["Content-Disposition"] = f'attachment; filename="{name}"' 64 # 可以兼容outlook 65 acc.add_header("Content-Disposition", "attachment", filename=("gb18030", "", name)) 66 return acc 67 68 def send_email(self): 69 # connect = "这是我使用python smtplib及email模块发送的邮件" # 正文 70 msg = MIMEMultipart() 71 # 括号里的对应发件人邮箱昵称、发件人邮箱账号 72 msg['From'] = formataddr([self.sender_name, self.sender]) 73 # 括号里的对应收件人邮箱昵称、收件人邮箱账号 74 msg['To'] = formataddr([self.attn_name, self.attn]) 75 # 邮件的主题,也可以说是标题 76 msg['Subject'] = self.subject 77 78 # 正文 79 msg.attach(MIMEText(self.connect, _charset='utf-8')) 80 # 附件 81 for file in self.files: 82 acc = self.accessory(file) 83 msg.attach(acc) 84 85 # 发件人邮箱中的SMTP服务器,端口是465 86 # server = smtplib.SMTP_SSL("smtp.qq.com", 465) 87 server = smtplib.SMTP_SSL(self.server, 465) 88 89 # 括号中对应的是发件人邮箱账号、邮箱密码 90 server.login(self.sender, self.sender_token) 91 # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件 92 server.sendmail(self.sender, [self.attn, ], msg.as_string()) 93 94 server.quit() # 关闭连接 95 96 def run(self): 97 # self.send_email() 98 try: 99 self.send_email() 100 return True 101 except Exception as e: 102 print(e.args)
标签:发邮件,sender,self,param,邮箱,attn,name From: https://www.cnblogs.com/hudieren/p/16792041.html