Python 如何向通过电子邮件发送的图片添加文件扩展名
完整的脚本每分钟用我的raspberry pi相机拍摄一张照片,并通过电子邮件发送到我的地址。图片在电子邮件中作为附件,但没有文件扩展名。 1.我需要补充什么才能使文件获得原始文件扩展名,并保存在raspberry上 或者如果可能的话: 2.我怎样才能得到嵌入在电子邮件中的图片。这会容易得多,所以我不必先在我的电脑上保护它们 我希望你们都明白我的意思,我的英语不是最好的:)Python 如何向通过电子邮件发送的图片添加文件扩展名,python,python-2.7,raspberry-pi,Python,Python 2.7,Raspberry Pi,完整的脚本每分钟用我的raspberry pi相机拍摄一张照片,并通过电子邮件发送到我的地址。图片在电子邮件中作为附件,但没有文件扩展名。 1.我需要补充什么才能使文件获得原始文件扩展名,并保存在raspberry上 或者如果可能的话: 2.我怎样才能得到嵌入在电子邮件中的图片。这会容易得多,所以我不必先在我的电脑上保护它们 我希望你们都明白我的意思,我的英语不是最好的:) 要将文件名添加到附件中,您需要将“Content Disposition”标题添加到该MIME部分,即将其添加到代码中:
要将文件名添加到附件中,您需要将
“Content Disposition”
标题添加到该MIME部分,即将其添加到代码中:
attachment = open(dat, 'rb')
image=MIMEImage(attachment.read())
attachment.close()
image.add_header('Content-Disposition', 'attachment; filename=filename.extension')
mail.attach(image)
要发送图像而不将其保存到文件中,您必须拥有图像内容并将其传递给MIMEImage
constructor。您当前正在从attachment.read()
中的文件中读取它们
因此,如果可以将图像二进制文件(而不是文件名)传递给函数,如下所示:
def sendMail(image_binary_data):
image=MIMEImage(image_binary_data)
image.add_header('Content-Disposition', 'attachment; filename=filename.extension')
mail.attach(image)
然后把它传过去,就像这样:
def sendMail(image_binary_data):
image=MIMEImage(image_binary_data)
image.add_header('Content-Disposition', 'attachment; filename=filename.extension')
mail.attach(image)
顺便说一句,如果您正在从文件中读取图像,以这种方式打开和读取文件更安全,以确保它始终正确关闭:
with open(dat, 'rb') as image_file:
image=MIMEImage(image_file.read())
# no need to close explicitly
image.add_header('Content-Disposition','attachment;filename=filename.jpg')非常有效,谢谢。现在我把这张照片作为电子邮件发送。jpg@rattionline酷。您也可以接受答案,以表明它解决了问题。