Python 发送带附件邮件客户端

参考自: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-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

receiver = '*****@qq.com'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '*****@163.com'
sender=username
with 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 attachment
attfile='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()


你可能感兴趣的:(Python 发送带附件邮件客户端)