Gmail API - plaintext word wrapping

后端 未结 2 881
天命终不由人
天命终不由人 2020-12-06 19:09

When sending emails using the Gmail API, it places hard line breaks in the body at around 78 characters per line. A similar question about this can be found here.

Ho

2条回答
  •  春和景丽
    2020-12-06 19:39

    I'm assuming you have a function similar to this:

    1. def create_message(sender, to, cc, subject, message_body):
    2.     message = MIMEText(message_body, 'html')
    3.     message['to'] = to
    4.     message['from'] = sender
    5.     message['subject'] = subject
    6.     message['cc'] = cc
    7.     return {'raw': base64.urlsafe_b64encode(message.as_string())}
    

    The one trick that finally worked for me, after all the attempts to modify the header values and payload dict (which is a member of the message object), was to set (line 2):

    • message = MIMEText(message_body, 'html') <-- add the 'html' as the second parameter of the MIMEText object constructor

    The default code supplied by Google for their gmail API only tells you how to send plain text emails, but they hide how they're doing that. ala... message = MIMEText(message_body)

    I had to look up the python class email.mime.text.MIMEText object. That's where you'll see this definition of the constructor for the MIMEText object:

    • class email.mime.text.MIMEText(_text[, _subtype[, _charset]]) We want to explicitly pass it a value to the _subtype. In this case, we want to pass: 'html' as the _subtype.

    Now, you won't have anymore unexpected word wrapping applied to your messages by Google, or the Python mime.text.MIMEText object

提交回复
热议问题