【问题标题】:Python - email send shows invalid syntax on Raspberry PiPython - 电子邮件发送在 Raspberry Pi 上显示无效语法
【发布时间】:2019-08-29 13:17:43
【问题描述】:

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

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

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

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

代码如下:


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)


【问题讨论】:

    标签: python email raspberry-pi mime


    【解决方案1】:

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

    您可以改用format 方法:

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

    【讨论】:

    • 你也应该去掉filename=后面的空格
    猜你喜欢
    • 1970-01-01
    • 2016-04-09
    • 2014-05-13
    • 2018-09-01
    • 2017-02-08
    • 2018-11-08
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多