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



我有一个python程序可以从gmail帐户发送电子邮件,该程序适用于Ubuntu,但不适用于Raspberry Pi。它显示下一个错误:

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

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

有什么东西与树莓派不匹配吗?有人可以告诉我如何解决这个问题吗?谢谢。

这是代码:


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-string是Python 3.6中的新功能。您的 Pi 可能使用的是旧版本。

您可以改用 format 方法:

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

最新更新