python发送邮件
Posted aaronthon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python发送邮件相关的知识,希望对你有一定的参考价值。
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header mail_host = "smtp.163.com" # 设置服务器 mail_user = "[email protected]" # 用户名 mail_pass = "python123" # 口令 sender = ‘[email protected]‘ receivers = [‘[email protected]‘,‘[email protected]‘] # 创建一个带附件的实例 message = MIMEMultipart() message[‘From‘] = ‘[email protected]‘ message[‘To‘] = ‘[email protected]‘ subject = ‘Python SMTP 邮件‘ message[‘Subject‘] = Header(subject, ‘utf-8‘) # 邮件正文内容 message.attach(MIMEText(‘这是菜鸟教程Python 邮件发送……‘, ‘plain‘, ‘utf-8‘)) # 构造附件1,传送当前目录下的 test.txt 文件 att1 = MIMEText(open(r‘safe.doc‘, ‘rb‘).read(), ‘base64‘, ‘utf-8‘) att1["Content-Type"] = ‘application/octet-stream‘ # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1["Content-Disposition"] = ‘attachment; filename="{0}"‘.format(‘safe.doc‘) message.attach(att1) # # 构造附件2,传送当前目录下的 runoob.txt 文件 # att2 = MIMEText(open(‘runoob.txt‘, ‘rb‘).read(), ‘base64‘, ‘utf-8‘) # att2["Content-Type"] = ‘application/octet-stream‘ # att2["Content-Disposition"] = ‘attachment; filename="runoob.txt"‘ # message.attach(att2) try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号 smtpObj.login(mail_user,mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print "邮件发送成功" except smtplib.SMTPException: print "Error: 无法发送邮件"
以上是关于python发送邮件的主要内容,如果未能解决你的问题,请参考以下文章
Javascript - 使用 HTML 片段通过电子邮件发送 JSON 输出