首页 > 解决方案 > 在 Python 3 中将电子邮件编码为 base64

问题描述

我正在尝试根据此处的说明使用 gmail 创建和发送电子邮件以编码为 base64。

我以这种方式创建消息:

import smtplib
from email.mime.text import MIMEText
import base64
to='name@gmail.com'
sender = 'me@email.com'
subject = 'Menu'
message_text = 'Spam'
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject

但是,当我转换为 base64

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

我收到此错误: TypeError: a bytes-like object is required, not 'str'

所以我试试这个:

msg = {'raw': base64.urlsafe_b64encode(message.as_bytes())}

但是,当我来发送消息时

result = (service.users().messages().send(userId=user_id, body=message)
           .execute())

我收到此错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-33-3c5bbd8af82c> in <module>
      8 send_message(service=service,
      9              user_id = 'MYEMAIL',
---> 10              message = msg)

<ipython-input-32-c2348e02ff45> in send_message(service, user_id, message)
     12   """
     13   #try:
---> 14   result = (service.users().messages().send(userId=user_id, body=message)
     15                .execute())
     16   print ('Message Id: %s' % message['id'])

~/gmail_env/lib/python3.7/site-packages/googleapiclient/discovery.py in method(self, **kwargs)
    787     headers = {}
    788     headers, params, query, body = model.request(headers,
--> 789         actual_path_params, actual_query_params, body_value)
    790 
    791     expanded_url = uritemplate.expand(pathUrl, params)

~/gmail_env/lib/python3.7/site-packages/googleapiclient/model.py in request(self, headers, path_params, query_params, body_value)
    156     if body_value is not None:
    157       headers['content-type'] = self.content_type
--> 158       body_value = self.serialize(body_value)
    159     self._log_request(headers, path_params, query, body_value)
    160     return (headers, path_params, query, body_value)

~/gmail_env/lib/python3.7/site-packages/googleapiclient/model.py in serialize(self, body_value)
    265         self._data_wrapper):
    266       body_value = {'data': body_value}
--> 267     return json.dumps(body_value)
    268 
    269   def deserialize(self, content):

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

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

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

~/anaconda3/lib/python3.7/json/encoder.py in default(self, o)
    177 
    178         """
--> 179         raise TypeError(f'Object of type {o.__class__.__name__} '
    180                         f'is not JSON serializable')
    181 

TypeError: Object of type bytes is not JSON serializable

那么,我如何格式化消息?(我认为这可能与 Python 3 / Python 2 的差异有关,但不能确定)

标签: pythonemailgmailsmtplibbase64url

解决方案


推荐阅读