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

Python - email send shows invalid syntax on Raspberry Pi

我有一个 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)


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

您可以改用format方法:

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