I am trying to send an email including an attachment via Python from my Raspberry Pi.
The following code (email.py) works when I'm using sudo python3 email.py
but does not via sudo python email.py
.
######WRITE EMAIL AND SEND
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import locale
locale.setlocale(locale.LC_TIME, "de_DE")
attachment = 0
fromaddr = 'MAIL@gmail.com'
toaddr = ['MAIL@gmail.com']
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = ", ".join(toaddr)
msg['Subject'] = 'ÄÖÜäöü'
body = 'Ääüäöü'
msg.attach(MIMEText(body, 'plain',_charset='latin-1'))
filename = 'Picture'
for file in os.listdir('/path/to/Pictures/'):
if file.__contains__('.png'):
a_file=file
attachment = open('/path/to/pi/Pictures/'+a_file, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename= %s' % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, 'Password')
text = msg.as_string()
print ('# Sending mail')
server.sendmail(fromaddr, toaddr, text)
server.quit()
print('# Mail Sent')
The Error I am getting when using the python method is:
SyntaxError: Non ASCII character \xc3 in file email.py on line XX but no encoding declared; see htttp://python.org/dev/peps/pep-0263/ for details.
The Umlaute ÄÖÜ...
are causing the problem.
I know that different python versions use different encodings as default and I python3 uses utf-8.
Somehow with python email.py
another encoding is used and I don't know how to change it.
I would like to know where I'd have to add specific encoding instructions into the code so that the code works on both python versions.