Python 发送带附件邮件客户端

来源:互联网 发布:数据自动传输的风速仪 编辑:程序博客网 时间:2024/05/20 02:24

参考自:http://blog.csdn.net/wyuan8913/article/details/6917873


想说一下坑了我不少时间的几点:

1.

from email.mime.multipart import MIMEMultipart 

我猜是因为版本的问题,之前使用MIMEMultipart的import不是这么写的。一直报错。

2.

content = MIMEText(text, 'plain','utf-8')

这里的'plain' 在参考链接里写的是'text',然后也一直报错,改成这样就成功了。

3.

password=password.strip('\n')

之前写成password.strip('\n'),发现一直没有去除比较末尾的换行符,还以为是strip失灵了,蛋疼了无数时间之后才改了错。。



#! /usr/local/ActivePython-3.2/bin#coding: utf-8import smtplibfrom email.mime.text import MIMETextfrom email.header import Headerfrom email.mime.multipart import MIMEMultipartreceiver = '*****@qq.com'subject = 'python email test'smtpserver = 'smtp.163.com'username = '*****@163.com'sender=usernamewith open('passwd.txt') as file:    password = file.readline()password=password.strip('\n')msg=MIMEMultipart('alternative')msg['Subject']='test message'text='你好'content = MIMEText(text, 'plain','utf-8') msg.attach(content)#create the attachmentattfile='buptsnow.jpg' att=MIMEText(open(attfile,'rb').read(),'base64', 'utf-8')att["Content-Type"] = 'application/octet-stream'att["Content-Disposition"] = 'attachment; filename="buptsnow.jpg"'msg.attach(att)smtp = smtplib.SMTP()smtp.connect('smtp.163.com')smtp.login(username, password)smtp.sendmail(sender, receiver, msg.as_string())smtp.quit()