python - 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)
解决方案
要将文件名添加到附件中,您需要将"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
推荐阅读
- php - Flutter http post请求返回html而不是json
- pandas - 根据来自另一个数据帧的多个条件从一个数据帧计算描述性统计数据
- c# - 通过制表符保存数据
- json - 数据库包含字符串中的引号,需要在 json 中使用,这会导致解析错误
- bazel - 如何确保构建不依赖于两个不同版本的外部依赖?
- arrays - 在C中的循环中覆盖全局char数组与全局char指针
- react-native - 从 React-Native 应用程序在 Facebook 应用程序中分享 URL 作为帖子
- javascript - 在 Typescript 中,`return x` 和 `return await x` 之间有区别吗?
- r - 您可以为函数作为 R 中的随机样本进行论证吗?
- php - Spatie Laravel Jetstream 中的 id '#' 没有任何作用