1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import time import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication
class Send_Mailbox(object): ''' host_server:主机地址-> 默认是QQ邮箱的主机地址 sender:发件人邮箱号 code:授权码 target:收件人邮箱号
title:邮件标题 content:邮件正文内容 filepath:邮件需要添加的附件地址 filename:邮件发送时的问价名 '''
def __init__(self, sender, code, target, host_server='smtp.qq.com'): self.host_server = host_server self.sender = sender self.code = code self.target = target
def send_out(self): smtp = smtplib.SMTP(self.host_server) try: smtp.login(self.sender, self.code) smtp.sendmail(self.sender, self.target, self.msg.as_string()) print("发送成功") except: print("发送失败,请检查校验码是否正确或者失效,邮箱地址是否正确")
def Set_mail_data(self, title, content, filepath=None, filename=None): if filepath: try: with open(filepath, 'rb') as f: if not filename: filename = filepath.split('/')[-1] attachment = MIMEApplication(f.read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg = MIMEMultipart() msg['Subject'] = title msg['From'] = self.sender msg['To'] = self.target msg.attach(MIMEText(content)) msg.attach(attachment) self.msg = msg except FileNotFoundError: print('文件路径错误') else: msg = MIMEText(content) msg['Subject'] = title msg['From'] = self.sender msg['To'] = self.target self.msg = msg
|