Khaled Al-Ansari Khaled Al-Ansari - 3 years ago 322
Python Question

Arabic characters in emails are getting decoded (Django)

I used this code to help me send emails from the linux server, everything is working fine except that if there was an Arabic character all of the email will be something like this: 2YrYs9mK2KfYq9i62KfZhNix2LPZig==

Note that I use python 3.

P.S.: in the code I added

.encode('utf-8')
in line 46 because I used to get this error 'str' does not support the buffer interface




UPDATE:

here's the data that I send using the email function

theemail = EmailMessage(subject, message , sender_email, recipients, headers = {
'Reply-To': sender_email, 'Content-Type':'text/html; charset=utf-8',
'From':'sales@e3lani.me', 'Return-Path':sender+' <'+sender_email+'>',
'Organization':sender, 'MIME-Version':'1.0', 'Content-Transfer-Encoding':'8bit',
'X-Priority':'3', 'X-Originating-IP':request.META.get('REMOTE_ADDR'),
'X-Mailer':'Python/3.4', 'Message-ID':make_msgid(), 'Date':datetime.datetime.now().time()})

theemail.content_subtype = "html" # though I'm still seeing the <br/> tag as a string instead of giving me a new line LOL
theemail.send()

Answer Source

I solved the problem, my problem was with the line I edited in the snippet code I used to sending emails

You see in the original code there was ps.stdin.write(email_message.message().as_string()) and I added .encode('utf-8') to turn the output to bytes! to solve the problem I added .as_bytes() instead of .as_string()

I searched for the reason and I found out that in Python3 bytes can be decoded to str, and str can be encoded to bytes, but the opposite is not!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download