UnicodeDecodeError Python 3.5.1电子邮件脚本

时间:2016-05-08 06:32:22

标签: python-3.x

我正在尝试向SMS网关电子邮件发送电子邮件+附件。但是我目前正在获得Unicode解码:Error'Charmap'编解码器无法解码位置60的字节0x8d

我不确定如何解决此问题,并对您的建议感兴趣。贝娄是我的代码和完全错误。

import smtplib, os

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


msg = MIMEMultipart()
msg['Subject'] = 'Cuteness'
msg['From'] = 'sample@outlook.com'
msg['To'] = '111111111@messaging.sprintpcs.com'
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>"""

1 个答案:

答案 0 :(得分: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)
相关问题