python发送带附件的邮件

来源:互联网 发布:js getparameter 编辑:程序博客网 时间:2024/05/25 23:59
import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.header import Header# 第三方 SMTP 服务mail_host="smtp.sina.com"  #设置服务器mail_user="hanliangwei123@sina.com"    #用户名mail_pass="**********"   #密码 sender = 'hanliangwei123@sina.com'receivers = ['835126606@qq.com']#创建一个带附件的实例message = MIMEMultipart()subject = 'Python SMTP 带附件邮件测试' #主题message['Subject'] = Header(subject, 'utf-8')# 构造附件1,传送当前目录下的 1.MP3 文件att = MIMEText(open('1.mp3', 'rb').read(), 'base64', 'utf-8')att["Content-Type"] = 'application/octet-stream'# 这里的filename可以任意写,写什么名字,邮件中显示什么名字att["Content-Disposition"] = 'attachment; filename="1.mp3"'message.attach(att)#邮件正文内容message.attach(MIMEText('这是Python 带附件的邮件发送测试……', 'plain', 'utf-8'))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: 无法发送邮件")

0 0
原创粉丝点击