Purpose: It is necessary to send a letter in the mail. The letter has Cyrillic characters.

Problem: the script works with Latin characters, but does not work in Cyrillic

Script:

import smtplib TEXT = "Кириллица \n"\ "Кириллица\n" TO = 'xxxxxx@gmail.com' SUBJECT = 'xxxx' # Gmail Sign In gmail_sender = 'xxxx@gmail.com' gmail_passwd = 'xxxxxx' server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(gmail_sender, gmail_passwd) BODY = '\r\n'.join(['To: %s' % TO, 'From: %s' % gmail_sender, 'Subject: %s' % SUBJECT, '', TEXT]) try: server.sendmail(gmail_sender, [TO], BODY) print('email sent') except: print('error sending mail') server.quit() 

Mistake:

 Traceback (most recent call last): File "C:/Users/babai/PycharmProjects/test/mail.py", line 47, in <module> server.sendmail(gmail_sender, [TO], BODY) File "C:\Program Files (x86)\Python36-32\lib\smtplib.py", line 854, in sendmail msg = _fix_eols(msg).encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode characters in position 63-74: ordinal not in range(128) 

As far as I understand the problem in the encoding. Is the smtplib module works only with ANSII ??

  • Possible duplicate question: Python 3.4 and Russian characters - Lex Hobbit
  • one
    Cyrillic is correctly displayed in the console, I think the problem is different - Babaikawow
  • aah, I understood MIMEText should be used - Lex Hobbit
  • Use the email module to get the text of the letter in mime format. See Encoding when sending a message - jfs
  • Problem solved. Used MIMEText. - Babaikawow

1 answer 1

Problem solved with MIMEText

Solution found here https://ru.stackoverflow.com/a/369479/237582

Thank you jfs

 # -*- coding: utf-8 -*- """Send email via smtp_host.""" import smtplib from email.mime.text import MIMEText from email.header import Header smtp_host = 'smtp.gmail.com' # yahoo login = "xxxxxx@gmail.com" password = "xxxxxxx" recipients_emails = "xxxxxx@gmail.com" msg = MIMEText('Спасибо', 'plain', 'utf-8') msg['Subject'] = Header('subject…', 'utf-8') msg['From'] = login msg['To'] = recipients_emails s = smtplib.SMTP(smtp_host, 587, timeout=10) s.set_debuglevel(1) try: s.starttls() s.login(login, password) s.sendmail(msg['From'], recipients_emails, msg.as_string()) finally: print(msg) s.quit()