0

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.pyanother 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.

Peter S
  • 625
  • 1
  • 9
  • 32
  • 1
    You can try including `from future import __unicode_literals__` at the top, then Python 2 will treat all strings as unicode. [See this SO question](https://stackoverflow.com/questions/23370025/what-is-unicode-literals-used-for). – user Jan 26 '18 at 18:04

1 Answers1

1

Python2 uses ASCII as default encoding. However, you can define the encoding to be used.

Add the following line to your script in order to hint your python to use a utf-8 encoding.

#coding=utf-8

You are not getting any error in case python3 because it uses utf-8 as default encoding.