Search code examples
pythonemailcharacter-encodingsmtpgmail

Python: sending mail with SMTP (to Gmail) and can't encode headers properly


I have a following snipper of code, partly borrowed from the stackoverflow users:

#!/usr/bin/env python
# -*- coding: iso-8859-2 -*-

def send_email(user, pwd, recipient, subject, body):
    import smtplib
    FROM = user
    TO = recipient if type(recipient) is list else [recipient]
    SUBJECT = subject
    TEXT = body
    # Prepare actual message
    message = """From: %s\nTo: %s\nSubject: =?iso-8859-2?Q?%s?=\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    print(message)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(user, pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print('successfully sent the mail')
    except:
        print("failed to send mail")

sentence='Koń'
send_email('login','pass','[email protected]',sentence.encode('iso-8859-2'),'test')

And it sends an email from a gmail account to another gmail account, however when I log in to the gmail page, the subject displays as

 b'Ko\xf1'

What am I doing wrong?


Solution

  • Recommended solution: Use Header function from email.header

    Explanation: RFC-2047 expects quoted printable encoded string inside =?iso-8859-2?Q?...?=.
    You put "raw" string.
    Valid utf-8 encoding encoding of koń is Subject: =?UTF-8?Q?ko=C5=84?=

    Suggestion: Consider uing utf-8 instead of iso-8859-2 if you can. utf-8 is more general (less regional) and resources cost (e.g. disk space) is little extra for "almost ascii" languages.