代码示例中的Gmail API错误 - 需要类似字节的对象,而不是' str'

时间:2017-04-11 17:22:57

标签: python api gmail

我将Gmail API合并到我正在制作的程序中,并且我收到了一个我无法解决的错误/我已经无法解决这个问题。能够找到在线答案。相关代码如下,以及错误:

from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
import base64
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
import os

def create_message(sender, to, subject, message_text):

    message = MIMEText(message_text)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    return {'raw': base64.urlsafe_b64encode(message.as_string())}

def send_message(service, user_id, message):

    message = (service.users().messages().send(userId=user_id, body=message).execute())
    print('Message Id: %s' % message['id'])
    return message

def send_email(orders):
    SCOPES = 'https://mail.google.com/'
    store = file.Storage('gmail.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = discovery.build('gmail','v1',http=creds.authorize(Http()))

    message_text = orders[0]

    created_message = create_message('from','to','subject', message_text)
    send_message(service, 'from', created_message)
send_email(['TEST'])


Traceback (most recent call last):
  File "test_email.py", line 50, in <module>
    schoolPing(['TEST'])
  File "test_email.py", line 47, in schoolPing
    created_message = create_message('from','to','subject', message_text)
  File "test_email.py", line 27, in create_message
    return {'raw': base64.urlsafe_b64encode(message.as_string())}
  File "/Users/Andre/anaconda/lib/python3.5/base64.py", line 119, in urlsafe_b64encode
    return b64encode(s).translate(_urlsafe_encode_translation)
  File "/Users/Andre/anaconda/lib/python3.5/base64.py", line 59, in b64encode
    encoded = binascii.b2a_base64(s)[:-1]
TypeError: a bytes-like object is required, not 'str'

1 个答案:

答案 0 :(得分:24)

找到解决方案,替换此行:

return {'raw': base64.urlsafe_b64encode(message.as_string())}

使用:

return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}

注意添加了 .encode() .decode()方法调用。

首先, str 对象被编码为 bytes 对象 - base64.urlsafe_b64encode 在Python 3中需要它(与 str <相比/ em> Python中的对象2)。

然后,必须将base64编码的 bytes 对象解码回 str 。这是必需的,因为 googleapiclient 库将在稍后的代码中尝试 json序列化,而 bytes 对象无法实现。