Skip to content Skip to sidebar Skip to footer

Using Python 3 And Gmail Api To Send Emails With Attachments, I End Up With Either Corrupted Files Or Connectionabortederror

I am using the Gmail API in Python 3 to send emails with attachments, based on their example code I've got the following to create the message: def create_message_with_attachment(

Solution 1:

The confusion with the correct encoding is due to the change from Python 2 to Python 3

The encoding procedure described in the Google documentation for sending emails is based on Python 2. I assume you are using Python 3.

To adapt the guide to the new Python version two modifications need to be implemented.

  1. Modify return {'raw': base64.urlsafe_b64encode(message.as_string())} to return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}. You have done this already.
  2. After msg.set_payload(contents) request you need to add an additional lineencoders.encode_base64(msg). This is what you were missing.

Now that you added it, mind that encoders is a module of the package email. If not already done, you need to add to your code from email import encoders

Post a Comment for "Using Python 3 And Gmail Api To Send Emails With Attachments, I End Up With Either Corrupted Files Or Connectionabortederror"