2016-05-08 43 views
0

我正在嘗試向SMS網關電子郵件發送電子郵件+附件。然而,我目前正在得到一個Unicode解碼:Error'Charmap'編解碼器無法解碼位置60的字節0x8dUnicodeDecodeError Python 3.5.1電子郵件腳本

我不知道如何去解決這個問題,並會對您的建議感興趣。波紋管是我的代碼和完整的錯誤。

import smtplib, os 

from email.mime.image import MIMEImage 
from email.mime.multipart import MIMEMultipart 


msg = MIMEMultipart() 
msg['Subject'] = 'Cuteness' 
msg['From'] = '[email protected]' 
msg['To'] = '[email protected]' 
msg.preamble = "Would you pet me? I'd Pet me so hard..." 

here = os.getcwd() 
file = open('cutecat.png')#the png shares directory with actual script 

for here in file: #Error appears to be in this section 
    with open(file, 'rb') as fp: 
     img = MIMImage(fp.read()) 
    msg.attach(img) 


s = smtplib.SMTP('Localhost') 
s.send_message(msg) 
s.quit() 

""" Traceback (most recent call last): 
    File "C:\Users\Thomas\Desktop\Test_Box\msgr.py", line 16, in <module> 
    for here in file: 
    File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 23, in decode 
    return codecs.charmap_decode(input,self.errors,decoding_table)[0] 
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 60: character maps to <undefined>""" 

回答

0

您試圖打開文件兩次。首先你有:

file = open('cutecat.png') 

打開文件的默認模式是在文本模式下讀取它們。通常情況下,您不想使用PNG文件等二進制文件。

然後你做:

for here in file: 
    with open(file, 'rb') as fp: 
     img = MIMImage(fp.read()) 
    msg.attach(img) 

您在第一線得到一個例外,因爲Python是試圖二進制文件的內容,文本解碼和失敗。發生這種情況的可能性非常高。二進制文件不太可能是標準編碼中的有效文本文件。

但即使這樣做,對於文件中的每一行,您都嘗試再次打開文件?這沒有道理!

你剛從examples複製/粘貼,特別是第三個?你應該注意到這個例子是不完整。該例中使用的變量pngfiles(以及哪個應該是是文件名的序列)沒有定義。

試試這個:

with open('cutecat.png', 'rb') as fp: 
    img = MIMImage(fp.read()) 
msg.attach(img) 

或者,如果您要包括多個文件:

pngfiles = ('cutecat.png', 'kitten.png') 
for filename in pngfiles: 
    with open(filename, 'rb') as fp: 
     img = MIMImage(fp.read()) 
    msg.attach(img) 
+0

哎呀!是的,我忘了我把它留在那裏,我很早就遇到了麻煩,忘記了解決這個問題。在這一天,我一直在做另一個項目8個小時,並開始變得懶惰。 – Villagesmithy