Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何为Gmail API正确地对MIMEText进行base64编码?_Python_Python 3.x_Encoding_Gmail Api_Google Api Python Client - Fatal编程技术网

Python 如何为Gmail API正确地对MIMEText进行base64编码?

Python 如何为Gmail API正确地对MIMEText进行base64编码?,python,python-3.x,encoding,gmail-api,google-api-python-client,Python,Python 3.x,Encoding,Gmail Api,Google Api Python Client,从: 以下代码示例演示如何创建MIME消息,将其编码为base64url字符串,并将其分配给消息资源的原始字段: 但如果我做了类似的事情 from email.MIMEText import MIMEText import base64 message = MIMEText('This is a test') message['to'] = 'test@gmail.com' message['from'] = 'tester@gmail.com' message['subject'] = 'Te

从:

以下代码示例演示如何创建MIME消息,将其编码为base64url字符串,并将其分配给消息资源的原始字段:

但如果我做了类似的事情

from email.MIMEText import MIMEText
import base64
message = MIMEText('This is a test')
message['to'] = 'test@gmail.com'
message['from'] = 'tester@gmail.com'
message['subject'] = 'Test'
body = {'raw': base64.urlsafe_b64encode(message.as_string())}
我得到
TypeError:需要一个类似字节的对象,而不是“str”
如果我这样做:

body = {'raw': base64.urlsafe_b64encode(message.as_bytes())}
message = (service.users().messages().send(userId='me', body=body)
               .execute())
我得到以下关于某些二进制文件不可json序列化的回溯:

~/env/lib/python3.5/site-packages/googleapiclient/discovery.py in method(self, **kwargs)
    792     headers = {}
    793     headers, params, query, body = model.request(headers,
--> 794         actual_path_params, actual_query_params, body_value)
    795 
    796     expanded_url = uritemplate.expand(pathUrl, params)

~/env/lib/python3.5/site-packages/googleapiclient/model.py in request(self, headers, path_params, query_params, body_value)
    149     if body_value is not None:
    150       headers['content-type'] = self.content_type
--> 151       body_value = self.serialize(body_value)
    152     self._log_request(headers, path_params, query, body_value)
    153     return (headers, path_params, query, body_value)

~/env/lib/python3.5/site-packages/googleapiclient/model.py in serialize(self, body_value)
    258         self._data_wrapper):
    259       body_value = {'data': body_value}
--> 260     return json.dumps(body_value)
    261 
    262   def deserialize(self, content):

/usr/lib/python3.5/json/__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    228         cls is None and indent is None and separators is None and
    229         default is None and not sort_keys and not kw):
--> 230         return _default_encoder.encode(obj)
    231     if cls is None:
    232         cls = JSONEncoder

/usr/lib/python3.5/json/encoder.py in encode(self, o)
    196         # exceptions aren't as detailed.  The list call should be roughly
    197         # equivalent to the PySequence_Fast that ''.join() would do.
--> 198         chunks = self.iterencode(o, _one_shot=True)
    199         if not isinstance(chunks, (list, tuple)):
    200             chunks = list(chunks)

/usr/lib/python3.5/json/encoder.py in iterencode(self, o, _one_shot)
    254                 self.key_separator, self.item_separator, self.sort_keys,
    255                 self.skipkeys, _one_shot)
--> 256         return _iterencode(o, 0)
    257 
    258 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

/usr/lib/python3.5/json/encoder.py in default(self, o)
    177 
    178         """
--> 179         raise TypeError(repr(o) + " is not JSON serializable")
    180 
    181     def encode(self, o):

TypeError: b'Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJ1cy1hc2NpaSIKTUlNRS1WZXJzaW9uOiAxLjAKQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzogN2JpdApGcm9tOiBUZXN0IFB5dGhvbgpUbzogcmFwaGFlbC5hLmR1bWFzQGdtYWlsLmNvbQpTdWJqZWN0OiBQbGVhc2Ugc3RheSBjYWxtLCB0aGlzIGlzIGEgdGVzdAoKVGhpcyBpcyBhIHRlc3Q=' is not JSON serializable
尝试:


base64.urlsafe\u b64encode
返回一个bytes对象(请参阅),因此在将其序列化为JSON之前,您需要将输出转换为字符串。

对于我来说,答案似乎与直觉相反:编码(message.as\u bytes()).decode(),但我们在这里,它可以工作。感谢您的回答!但是为什么我们要对它进行编码,然后再对它进行解码呢?我的mimetext是:from email.mime.text import mimetext
~/env/lib/python3.5/site-packages/googleapiclient/discovery.py in method(self, **kwargs)
    792     headers = {}
    793     headers, params, query, body = model.request(headers,
--> 794         actual_path_params, actual_query_params, body_value)
    795 
    796     expanded_url = uritemplate.expand(pathUrl, params)

~/env/lib/python3.5/site-packages/googleapiclient/model.py in request(self, headers, path_params, query_params, body_value)
    149     if body_value is not None:
    150       headers['content-type'] = self.content_type
--> 151       body_value = self.serialize(body_value)
    152     self._log_request(headers, path_params, query, body_value)
    153     return (headers, path_params, query, body_value)

~/env/lib/python3.5/site-packages/googleapiclient/model.py in serialize(self, body_value)
    258         self._data_wrapper):
    259       body_value = {'data': body_value}
--> 260     return json.dumps(body_value)
    261 
    262   def deserialize(self, content):

/usr/lib/python3.5/json/__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    228         cls is None and indent is None and separators is None and
    229         default is None and not sort_keys and not kw):
--> 230         return _default_encoder.encode(obj)
    231     if cls is None:
    232         cls = JSONEncoder

/usr/lib/python3.5/json/encoder.py in encode(self, o)
    196         # exceptions aren't as detailed.  The list call should be roughly
    197         # equivalent to the PySequence_Fast that ''.join() would do.
--> 198         chunks = self.iterencode(o, _one_shot=True)
    199         if not isinstance(chunks, (list, tuple)):
    200             chunks = list(chunks)

/usr/lib/python3.5/json/encoder.py in iterencode(self, o, _one_shot)
    254                 self.key_separator, self.item_separator, self.sort_keys,
    255                 self.skipkeys, _one_shot)
--> 256         return _iterencode(o, 0)
    257 
    258 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

/usr/lib/python3.5/json/encoder.py in default(self, o)
    177 
    178         """
--> 179         raise TypeError(repr(o) + " is not JSON serializable")
    180 
    181     def encode(self, o):

TypeError: b'Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJ1cy1hc2NpaSIKTUlNRS1WZXJzaW9uOiAxLjAKQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzogN2JpdApGcm9tOiBUZXN0IFB5dGhvbgpUbzogcmFwaGFlbC5hLmR1bWFzQGdtYWlsLmNvbQpTdWJqZWN0OiBQbGVhc2Ugc3RheSBjYWxtLCB0aGlzIGlzIGEgdGVzdAoKVGhpcyBpcyBhIHRlc3Q=' is not JSON serializable
b64_bytes = base64.urlsafe_b64encode(message.as_bytes())
b64_string = b64_bytes.decode()
body = {'raw': b64_string}