Python发送邮件 发表于 2018-06-20 | 分类于 Python | | 阅读次数: | 字数统计: 273 字 | 阅读时长 ≈ 1 分钟 最近一个需求是使用Python自带的smtplib模块发送邮件,以下便是代码部分。 1234567891011121314151617181920212223242526272829303132333435363738394041424344import smtplibfrom email.mime.text import MIMETextfrom email.header import Headerfrom email.mime.multipart import MIMEMultipartdef send_mail(title, contents, receivers, path, filename): mail_host = "smtp.163.com" # 设置服务器 mail_user = "***@163.com" # 用户名 mail_pass = "***" # 口令 sender = '***@163.com' # 和mail_user保持一致 # 创建一个带附件的实例 message = MIMEMultipart() message['From'] = sender message['To'] = ','.join(receivers) message['Cc'] = sender subject = 'Python发送邮件' message['Subject'] = Header(subject, 'utf-8') # 邮件正文内容 message.attach(MIMEText(contents, 'plain', 'utf-8')) # 构造附件 attach_file = MIMEText(open(path, 'rb').read(), 'base64', 'utf-8') attach_file["Content-Type"] = 'application/octet-stream' # filename自定义 下面是实现附件可带中文 attach_file.add_header('Content-Disposition', 'attachment', filename='{}'.format(Header(filename, 'utf-8'))) # attach_file["Content-Disposition"] = f'attachment; filename={filename}' message.attach(attach_file) try: result = True errors = '' smtpObj = smtplib.SMTP_SSL(mail_host, 465) smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) except Exception as error: # 捕捉全部异常 result = False errors = error return result, errors 代如果不合理请留言指正。 知识就是财富 如果您觉得文章对您有帮助, 欢迎请我喝杯水! 打赏 微信支付