Search code examples
pythonemailheadermime

How do I change my Content-Transfer-Encoding header in Python?


This is my code right now:

from email.MIMEText import MIMEText
body = "helloworld"
msg = MIMEText(body, 'plain')
msg['Subject']= subject
msg['From']   =  from_field['name'] + ' <'+from_field['email']+'>'
msg['Date'] =  datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')


#other code here for connecting to SMTP
conn.sendmail(from_field['email'],[to_email], msg.as_string()) #finally send the email

My current code produces the following headers:

Content-Transfer-Encoding: 7bit
Content-Type: text/plain; charset="us-ascii" 

However, I want my code to produce the following:

Content-Transfer-Encoding: quoted-printable 
Content-Type: text/plain; charset=iso-8859-1

How can I modify my MIMEText to do this?


Solution

  • Specifying _charset changes the Content-Transfer-Encoding and Content-Type

    >>> import datetime
    >>> from email.MIMEText import MIMEText
    >>> body = "helloworld"
    >>> msg = MIMEText(body, 'plain', _charset='iso-8859-1')
    >>> msg['Subject'] = 'asdf'
    >>> msg['From'] = 'name <username@example.com>'
    >>> msg['Date'] = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')
    >>> print msg
    From nobody Sun Oct 13 06:22:32 2013
    Content-Type: text/plain; charset="iso-8859-1"
    MIME-Version: 1.0
    Content-Transfer-Encoding: quoted-printable
    Subject: asdf
    From: name <username@example.com>
    Date: Sun, 13 Oct 2013 06:22:30
    
    helloworld