首页 > 解决方案 > How to add file extension to pictures send via email

问题描述

The complete script makes a picture with my raspberry pi camera every minute and sends it via email to my adress. The picture is as an attachment in the email but it has no file extension. 1. What do i have to add that the file get the original file extension that they are saved on the raspberry.

Or if its possible: 2. How can I get the pictures embed in the email. This would be much easier so I don`t have to safe them first on my pc.

I hope you all know what I mean, my englich is not the best :)

def sendMail(data):
    global texte
    mail = MIMEMultipart()
    mail['Subject'] = "Pictures from home"
    mail['From'] = fromaddr
    mail['To'] = toaddr
    mail.attach(MIMEText(body, 'plain'))

    dat='%s.jpg'%data
    attachment = open(dat, 'rb')
    image=MIMEImage(attachment.read())
    attachment.close()
    mail.attach(image)
    server = smtplib.SMTP('smtp.web.de', 587)
    server.starttls()
    server.login(fromaddr, "PASSWORD")
    text = mail.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()


    movepic(data)

标签: pythonpython-2.7raspberry-pi

解决方案


要将文件名添加到附件中,您需要将"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构造函数。您当前正在从attachment.read().

因此,如果您可以将图像二进制文件(而不是文件名)传递给函数,如下所示:

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

推荐阅读