0

I want to send alert email in Persian language using python3. but i encounter with the following error:

Sending mail failed; 'ascii' codec can't encode characters in position 115-120: ordinal not in range(128)

and this is my python script:

import sys
import smtplib
import datetime

mail_from = "test@example.com"
rcpt_to = sys.argv[1]  # mail receiver

username = "test@example.com"
password = "P@ssW0rD"
smtpServer = "MAIL_SERVER_IP_ADDRESS"

subject = sys.argv[2]
date = datetime.datetime.now().strftime("%d-%m-%Y %H:%M")
message_body = 'سلام'

msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % (mail_from, rcpt_to, subject, date, message_body)

try:
    conn = smtplib.SMTP(smtpServer, 25)
    conn.set_debuglevel(False)
    conn.login(username, password)
    try:
        conn.sendmail(mail_from, rcpt_to, msg)
    finally:
        conn.close()
except Exception as exc:
    sys.exit("Sending mail failed; %s" % str(exc))

How can i resolve this problem? Thanks

DearPython
  • 313
  • 1
  • 2
  • 5
  • And if you try `message_body = u'سلام'`? – Nander Speerstra Jul 20 '16 at 09:08
  • Yes, i test it and i receive the same error. – DearPython Jul 20 '16 at 09:29
  • Sorry, I meant `'سلام'.encode('utf-8')` (make it unicode in the correct way). – Nander Speerstra Jul 20 '16 at 09:33
  • 1
    Please read [this answer on a similar question](http://stackoverflow.com/a/5387966/5488275): ASCII only contains the first 127 Unicode characters and yours isn't part if the first 127. This is why you get the error. – Nander Speerstra Jul 20 '16 at 09:36
  • The email will be send if i use " 'سلام'.encode('utf-8') ", but the body of my email is " b'\xd8\xb3\xd8\xb4\xd8\xb3\xdb\x8c\xd8\xa8\xd8\xb4' ". – DearPython Jul 20 '16 at 09:41
  • 1
    [From the smtplib Help](https://docs.python.org/3/library/smtplib.html): "msg may be a string containing characters in the ASCII range, or a byte string". The first is not possible for your characters, the second is what you now have. I do not know how/whether smtplib can convert bytes back to 'readable' format. – Nander Speerstra Jul 20 '16 at 09:52

0 Answers0