Python-电子邮件发送在Raspberry Pi上显示无效的语法

时间:2019-04-08 11:39:04

标签: python email raspberry-pi mime

我有一个python程序可以从在Ubuntu上运行的gmail帐户发送电子邮件,但不能在Raspberry Pi上运行。它显示下一个错误:

    f"attachment; filename= {filename}",  <=it shows problem on this double quotation.

当我从该字符串的开头删除f时,它似乎不再显示错误消息,但是这将粉碎文件以进行发送,并且从电子邮件下载后无法打开它。

是否存在与Raspberry Pi不匹配的内容?有人可以告诉我如何解决这个问题吗?谢谢。

代码如下:


import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "Detection!"
body = "There was a detection from Pi"
sender_email = "example@gmail.com"
receiver_email = "example2@gmail.com"
password = "example"

# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach(MIMEText(body, "plain"))

filename = "image.jpeg"  # In same directory as script

# Open PDF file in binary mode
with open(filename, "rb") as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode file in ASCII characters to send by email
encoders.encode_base64(part)

# Add header as key/value pair to attachment part
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}", # HERE IS THE INVALID SYNTAX ERROR
)

# Add attachment to message and convert message to string
message.attach(part)
text = message.as_string()

# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, text)


1 个答案:

答案 0 :(得分:1)

f字符串是Python 3.6中的新增功能。您的Pi可能使用的是旧版本。

您可以改用format方法:

part.add_header(
    "Content-Disposition",
    "attachment; filename={}".format(filename),
)