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()


發佈了225 篇原創文章 · 獲贊 30 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章