user11040244
user11040244

Reputation:

Python - email send shows invalid syntax on Raspberry Pi

I have a python program to send emails from gmail account that works on Ubuntu, but not on Raspberry Pi. It shows next error:

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

It looks like that it stops showing error msg when I delete f from the start of that string, but that will crush file for sending and I'm not able to open it after downloading from email.

Is there something that doesn't match Raspberry Pi? Could someone please tell me how to solve this problem? Thanks.

here is the code:


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)


Upvotes: 0

Views: 1250

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599648

f-strings were new in Python 3.6. Your Pi is presumably using an older version.

You can use the format method instead:

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

Upvotes: 1

Related Questions