beano
beano

Reputation: 952

How to encode 'Sender Name' with MIMEText

When sending via the Gmail API, is it possible to include special characters within the sender name?

For example, when trying to send with the following code, the sender name is omitted and it only displays the email address.

When including an ascii based sender name, it works without issue.

import base64
from email.mime.text import MIMEText

fromName = u'«ταБЬℓσ»' #contains special characters
fromEmail = '[email protected]'

message = MIMEText(bodyHtml, 'html', 'utf-8')
message['From'] = u'{} <{}>'.format(fromName, fromEmail).encode('utf-8')
message['to'] = unicode(toEmail)
message['reply-to'] = unicode(replyTo)
message['subject'] = unicode(subject)
message_obj = {'raw': base64.urlsafe_b64encode(message.as_string())}

Upvotes: 1

Views: 772

Answers (1)

beano
beano

Reputation: 952

To a newb like me, this was difficult to work out. The key aspect I was missing originally, is that the sender name needed to be in a quoted printable format for it to be recognised.

The RFC 2047 documentation and this question helped me work it out.

Hope this helps others in the future.

import base64
import quopri
from email.mime.text import MIMEText

message = MIMEText(bodyHtml, 'html', 'utf-8')
message['From'] = "=?utf-8?q?" + quopri.encodestring(str(fromName.encode('utf-8'))) + "?=" + " <{}>".format(fromEmail)
message['to'] = unicode(toEmail)
message['reply-to'] = unicode(replyTo)
message['subject'] = unicode(subject)
message_obj = {'raw': base64.urlsafe_b64encode(message.as_string())}

Upvotes: 1

Related Questions