2
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage

msg = MIMEMultipart('multipart/related')

fromaddr = 'from@gmail.com'
toaddrs = 'to@gmail.com'


#provide gmail user name and password
username = 'to@gmail.com'
password = 'messifan'

filename = "1.jpg"
f = file(filename)
attachment = MIMEImage(f.read()) # error here
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
.
.
server.sendmail(fromaddr, toaddrs, msg.as_string())   

我正在使用此代码发送电子邮件。我可以使用此脚本附加文本文件。(将 MIMEImage 转换为 MIMEtext)。但无法附加图像。错误是无法猜测图像 mime 子类型

4

3 回答 3

10

尝试

attachment = MIMEImage(f.read(), _subtype="jpeg") # error here
于 2013-12-11T07:39:05.880 回答
7

这里有点猜测,但也许尝试以二进制模式打开文件?

f = file(filename, 'rb')
于 2013-04-23T16:37:15.183 回答
2

Looks to me like you created a "file" object, but you never opened it.

Where you have:

f = file(filename)
attachment = MIMEImage(f.read()) # error here

I think you instead need:

fp = open(filename, 'rb')
attachment = MIMEImage(fp.read())
fp.close()
于 2014-05-28T15:15:03.747 回答