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

问题描述 投票:0回答:1

我有一个python程序来发送来自gbu帐户的电子邮件,该电子邮件适用于Ubuntu,但不适用于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 = "[email protected]"
receiver_email = "[email protected]"
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)


python email raspberry-pi mime
1个回答
1
投票

f-strings在Python 3.6中是新的。你的Pi大概是使用旧版本。

您可以使用format方法:

part.add_header(
    "Content-Disposition",
    "attachment; filename={}".format(filename),
)
© www.soinside.com 2019 - 2024. All rights reserved.