0

I have a question related to last answer in How do I send HTML Formatted emails, through the gmail-api for python but unfortunately the answer does not work for me. If I attach both the 'plain' and 'html' parts, it only accepts the LAST 'attach' call I make. That is, if I attach as 'plain' AFTER 'html', it only sends as 'plain',(which looks unappealing on devices/apps with HTML rendering)., but if I attach the 'html' AFTER 'plain', it only sends the 'html' format (which looks bad on devices/apps without HTML rendering). Unlike the person who posted that question, I do need both parts because some of the devices/apps that receive my emails do not render HTML and need the plain text part.

This is not a problem if I used 'smtplib' instead of GMAIL-API, but I want to use gmail api for better security in my app.

Here is my code:

   message = MIMEMultipart('alternative')

   message['to'] = to_email
   message['from'] = from_email
   message['subject'] = subject

   body_plain = MIMEText(email_body,'plain')
   message.attach(body_plain)
   
   body_html_format="<u><b>html:<br>"+email_body+"</b></u>"
   body_html = MIMEText(body_html_format,'html')
   message.attach(body_html)  # PROBLEM: Will only send as HTML since this was added LAST.

   raw_string = base64.urlsafe_b64encode(message.as_bytes()).decode()

   request = service.users().messages().send(userId='my.email@gmail.com',body={'raw':raw_string})
   message = request.execute()

Thanks and regards, Doug

  • I deleted my answer because it was obviously wrong, deeply apologies about that. I'm trying to find any useful information in the Gmail API documentation but I have not found anything related to your problem. The most similar thing is this page about [multipart upload](https://developers.google.com/gmail/api/guides/uploads#multipart) being thought as a way to upload attachments to file. If I can ask, couldn't you just embed the plain text to the html? – Raserhin Aug 21 '20 at 07:26
  • @Doug Nintzel: Are you still experiencing this issue or did you already find a solution yourself? – ziganotschka Aug 31 '20 at 08:57
  • Raserhin, thanks for checking. @ziganotschka, yes, I am still facing this problem, but I have filed a bug against the GMail API client python module. So far they have not helped, but they are engaging. Thanks. – Doug Nintzel Sep 19 '20 at 16:59
  • Does it work if you define `raw_string =base64.urlsafe_b64encode( bytes(message.as_string(),"utf-8")).decode("utf-8")`? – ziganotschka Sep 21 '20 at 13:10

0 Answers0