python 发送邮件(带附件)

mac2025-09-11  17

def sendEmail(content, receiver,title,filename): host = 'smtp.exmail.qq.com' port = 465 sender = '邮箱地址' pwd = '邮箱密码'   #html代码 mailContent =""" <html> <head> <meta http-equiv=\"Content-Language\" content=\"zh-cn\"> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=GB2312\"> </head> <body> """+content+""" <br><br><br> <p>This message contains information which may be confidential and privileged. Unless you are the addressee (or authorized to receive for the addressee), you may not use, copy or disclose to anyone the message or any information contained in the message.</p> </body> </html> """ msg = MIMEMultipart() msg.attach(MIMEText(mailContent, "html", "utf-8")) for file in filename: # 构造附件att1,若是要带多个附件,可根据下边的格式构造 att1 = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8') att1['Content-Type'] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment; filename="%s"' % os.path.basename(file) msg.attach(att1) msg['subject'] = title msg['from'] = sender msg['to'] = receiver try: s = smtplib.SMTP_SSL(host, port) s.login(sender, pwd) s.sendmail(sender, receiver, msg.as_string()) print('sent email success') except smtplib.SMTPException: print('Error.sent email fail')
最新回复(0)