Hello everyony,
I have a Python-Script which worked fine under Python2 but when I try to run it in Python3 I get the following error:
This is one of my scripts:
I have a Python-Script which worked fine under Python2 but when I try to run it in Python3 I get the following error:
Traceback (most recent call last):
File "debug2.py", line 49, in <module>
sender.sendmail(sendTo, emailSubject, emailContent)
File "debug2.py", line 39, in sendmail
session.sendmail(GMAIL_USERNAME, recipient, headers + "\r\n\r\n" + content)
File "/usr/lib/python3.7/smtplib.py", line 855, in sendmail
msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 131-133: ordinal not in range(128)Since Python2 reached it's EOL I wanted to "update" my scripts to Python3 and most of them worked out pretty well.This is one of my scripts:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import smtplib
import time
f1 = open("../index/mail.txt","r")
mail = f1.read() [:-1]
f2 = open("../index/passwd.txt","r")
passwd = f2.read() [:-1]
f3 = open("../index/receiver.txt","r")
receiver = f3.read() [:-1]
#Email Variables
SMTP_SERVER = 'smtp.gmail.com' #Email Server (don't change!)
SMTP_PORT = 587 #Server Port (don't change!)
GMAIL_USERNAME = mail #change this to match your gmail account
GMAIL_PASSWORD = passwd #change this to match your gmail password
class Emailer:
def sendmail(self, recipient, subject, content):
#Create Headers
headers = ["From: " + GMAIL_USERNAME, "Subject: " + subject, "To: " + recipient,
"MIME-Version: 1.0", "Content-Type: text/html"]
headers = "\r\n".join(headers)
#Connect to Gmail Server
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo()
#Login to Gmail
session.login(GMAIL_USERNAME, GMAIL_PASSWORD)
#Send Email & Exit
session.sendmail(GMAIL_USERNAME, recipient, headers + "\r\n\r\n" + content)
session.quit
sender = Emailer()
sendTo = receiver
emailSubject = "Subject"
emailContent = "ÄÖÜ"
#Sends an email to the "sendTo" address with the specified "emailSubject" as the subject and "emailConten$
sender.sendmail(sendTo, emailSubject, emailContent)I only get the error when I use something like an 'äöü' which is pretty common for the german language. In Python2 I had a similiar issue which I could resolve by using the coding:utf-8line in the head. How do you solve this in Python3?
