Python Forum
ASCII-Codec in Python3 [SOLVED]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ASCII-Codec in Python3 [SOLVED]
#1
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:

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-8
line in the head. How do you solve this in Python3?
Reply
#2
The documentation of smtplib.SMTP.sendmail() says
Quote:msg may be a string containing characters in the ASCII range, or a byte
string. A string is encoded to bytes using the ascii codec, and lone
\r and \n characters are converted to \r\n characters.
As you want to send a string containing characters outside the ASCII range, I suggest that you encode the string manually using another encoding, such as utf8, so try this
msg = (headers + "\r\n\r\n" + content).encode('utf8')
session.sendmail(GMAIL_USERNAME, recipient, msg)
Reply
#3
(Jul-07-2021, 06:39 PM)Gribouillis Wrote: The documentation of smtplib.SMTP.sendmail() says
Quote:msg may be a string containing characters in the ASCII range, or a byte
string. A string is encoded to bytes using the ascii codec, and lone
\r and \n characters are converted to \r\n characters.
As you want to send a string containing characters outside the ASCII range, I suggest that you encode the string manually using another encoding, such as utf8, so try this
msg = (headers + "\r\n\r\n" + content).encode('utf8')
session.sendmail(GMAIL_USERNAME, recipient, msg)

Thanks for your reply.
I edited the ending of my file to this (I hope you meant that).

        #Send Email & Exit
        msg = (headers + "\r\n\r\n" + content).encode('utf8')
        session.sendmail(GMAIL_USERNAME, recipient, msg)
        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)
When I try to execute it I get the following error:

  File "debug2.py", line 40
    msg = (headers + "\r\n\r\n" + content).encode('utf8')
                                                        ^
TabError: inconsistent use of tabs and spaces in indentation
I don't see the error here tbh.
Reply
#4
Make sure the python file is indented with 4 spaces instead of tab characters. You can use the old but excellent reindent command to reindent the program, or a more recent tool such as the black module, or replace the tab characters by 4 space characters with your editor.

Also note that your editor can be configured to enter 4 spaces when you hit the tabulation key. Use this configuration for Python programming.
Reply
#5
(Jul-07-2021, 07:03 PM)Gribouillis Wrote: Make sure the python file is indented with 4 spaces instead of tab characters. You can use the old but excellent reindent command to reindent the program, or a more recent tool such as the black module, or replace the tab characters by 4 space characters with your editor.

Also note that your editor can be configured to enter 4 spaces when you hit the tabulation key. Use this configuration for Python programming.

Yeah, of course there was a tab, stupid me Doh
Thanks for the help, now it works Smile
Reply
#6
I am using python 3.9.6 still I am getting same issue :

ascii' codec can't encode character '\\xa0' in position 38: ordinal not in range(128)

class SendEmailView(generics.GenericAPIView):
    def post(self, request):
        serializer = SendEmailSerializer(data=request.data)
        if serializer.is_valid():
            to_email = serializer.validated_data['to_email']
            subject = serializer.validated_data['subject']
            message = serializer.validated_data['message']

            # Clean non-ASCII characters like \xa0
            to_email = to_email
            subject = subject
            message = message.encode('utf-8')

            try:
                send_mail(
                    subject,
                    message,
                    settings.EMAIL_HOST_USER,
                    [to_email],

                )
                return Response({'detail': 'Email sent successfully'}, status=status.HTTP_200_OK)
            except Exception as e:
                error_msg = str(e).encode('utf-8').decode()
                return Response({'error': error_msg}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Reply
#7
(Jul-19-2025, 04:26 AM)SagarSwag Wrote: I am using python 3.9.6 still I am getting same issue :
We only have a part of the error message. You could try
error_msg = traceback.format_exc()
to get a more complete error message.

Perhaps the bad character is in the subject of the message? Try encoding the subject.
« We can solve any problem by introducing an extra level of indirection »
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [solved] how to delete the 10 first lines of an ascii file paul18fr 7 4,178 Aug-07-2024, 08:18 PM
Last Post: Gribouillis
Question UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 562: ord ctrldan 23 13,057 Apr-24-2023, 03:40 PM
Last Post: ctrldan
  [SOLVED] [Debian] UnicodeEncodeError: 'ascii' codec Winfried 1 2,339 Nov-16-2022, 11:41 AM
Last Post: Winfried
  UnicodeEncodeError: 'ascii' codec can't encode character '\xfd' in position 14: ordin Armandito 6 5,536 Apr-29-2022, 12:36 PM
Last Post: Armandito
  codec for byte transparency Skaperen 7 6,295 Sep-25-2020, 02:20 AM
Last Post: Skaperen
  'charmap' codec louis216 4 27,037 Jun-30-2020, 06:25 AM
Last Post: louis216
  Which codec can help me decode the html source? vivekagrey 4 5,199 Jan-10-2020, 09:33 AM
Last Post: DeaD_EyE
  Gnuradio python3 is not compatible python3 xmlrpc library How Can I Fix İt ? muratoznnnn 3 7,168 Nov-07-2019, 05:47 PM
Last Post: DeaD_EyE
  unicodedecodeerror:utf codec can't decode byte 0xe3 in position 1 mariolopes 3 4,591 Oct-14-2019, 10:17 PM
Last Post: mariolopes
  unicodeencodeerror 'charmap' codec can't encode characters in position panoss 3 43,032 Jan-28-2017, 03:27 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020