question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Update "Sending e-mail" docs to work with Python 3

See original GitHub issue

The documentation for sending e-mails doesn’t seem to work when using Python 3. Also, I can’t seem to get e-mail sending working with Python 3 when sending binary (PDF) attachments. The code I’m using worked with Python 2. Details are below.

The Gmail REST API documentation for sending e-mail says to do the following:

raw = base64.urlsafe_b64encode(mime.as_string())
body = {'raw': raw}
messages = service.users().messages()
message = messages.send(userId='me', body=body).execute()

However, this code results in the following error:

File "/Users/chris/dev/.virtualenvs/my_package/lib/python3.4/base64.py", line 121, in urlsafe_b64encode
  return b64encode(s).translate(_urlsafe_encode_translation)
File "/Users/chris/dev/.virtualenvs/my_package/lib/python3.4/base64.py", line 62, in b64encode
  encoded = binascii.b2a_base64(s)[:-1]
TypeError: 'str' does not support the buffer interface

Changing as_string() in the above to as_bytes():

raw = base64.urlsafe_b64encode(mime.as_bytes())
body = {'raw': raw}
messages = service.users().messages()
message = messages.send(userId='me', body=body).execute()

results in the following error:

File "/Users/chris/dev/.virtualenvs/my_package/lib/python3.4/site-packages/googleapiclient/discovery.py", line 691, in method
  actual_path_params, actual_query_params, body_value)
File "/Users/chris/dev/.virtualenvs/my_package/lib/python3.4/site-packages/googleapiclient/model.py", line 149, in request
  body_value = self.serialize(body_value)
File "/Users/chris/dev/.virtualenvs/my_package/lib/python3.4/site-packages/googleapiclient/model.py", line 258, in serialize
  return json.dumps(body_value)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/__init__.py", line 230, in dumps
  return _default_encoder.encode(obj)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/encoder.py", line 192, in encode
  chunks = self.iterencode(o, _one_shot=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/encoder.py", line 250, in iterencode
  return _iterencode(o, 0)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/encoder.py", line 173, in default
  raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'Q29ud...TY9PS0tCg==' is not JSON serializable

If I add raw = raw.decode() to ensure that raw is a string in Python 3 as opposed to bytes, then the e-mail does get sent. However, the PDF attachment now seems to be corrupted:

raw = base64.urlsafe_b64encode(mime.as_bytes())
raw = raw.decode()
body = {'raw': raw}
messages = service.users().messages()
message = messages.send(userId='me', body=body).execute()

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Reactions:17
  • Comments:28 (3 by maintainers)

github_iconTop GitHub Comments

12reactions
divinedragoncommented, Apr 7, 2017

Just in case still faces an issue like me, here is my code.

with open(file, 'rb') as pdf_file:
      pdf = MIMEBase('application', "pdf")
      pdf.set_payload(pdf_file.read())
      encoders.encode_base64(pdf)
      pdf.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))

message.attach(pdf)

return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
6reactions
ghostcommented, Oct 5, 2017

Still same issue in October 2017!

here is a full working python 3.6 script for sending messages with attatchments (you just need to fill out the arguments for create_message_with_attatchment):

https://pastebin.com/aCQaVavQ

I spent 2 hours to make it work, quite sad that they don’t update their documentation.

Read more comments on GitHub >

github_iconTop Results From Across the Web

email: Examples — Python 3.11.1 documentation
Here are a few examples of how to use the email package to read, write, and send simple email messages, as well as...
Read more >
Sending Emails With Python - Real Python
Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package.
Read more >
Send Emails With Python [UPDATED] - YouTube
In this video you'll learn the new way on how to send emails with python.Download All Free Resources ...
Read more >
Mail API for Python 3 - App Engine - Google Cloud
The Mail API for Python 3 can be used to receive emails and bounce notifications. ... module and use the InboundEmailMessage class to...
Read more >
How to Easily Automate Emails with Python
1. Turn On 2-Step Verification · 2. Sending Email with Python - Import the libraries and set email sender and receiver - Set...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found