Python 3.5を使いGoogle Gmail APIを使ってREST経由でメールを取得するところはできました。
ただ、メール本文がエンコードされているのでデコードしようとしていますが以下のエラーメッセージが現れ、対応方法に苦慮しています。
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x87 in position 1: invalid start byte
コードは以下のとおりです。
python
1# coding:utf-8 2# Getting Gmail body # 3 4import requests 5import string 6import base64 7import email 8import json 9import codecs 10import sys 11 12Msg_id = ['"Msg_id_1"', '"Msg_id_2"', '"Msg_id_3"'] 13Gmail_list ='https://www.googleapis.com/gmail/v1/users/me/messages/' 14 15payload = {'grant_type': 'refresh_token', 16 'refresh_token': '<---Token--->', 17 'client_id': '<---client_id----->', 18 'client_secret': '<----client_secret---->', 19 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob', 20 'scope': 'https://mail.google.com/' 21 } 22r = requests.post("https://accounts.google.com/o/oauth2/token", data=payload) 23key_json = json.loads(r.text) 24key = (json.dumps(key_json['access_token'], sort_keys = True, indent = 4)) 25data = {'Authorization': 'Bearer ' + key.strip('"')} 26Gmail_body ='https://www.googleapis.com/gmail/v1/users/me/messages/' + Msg_id[1].strip('"') 27r3 = requests.get(Gmail_body, headers=data) 28Gmail_json = json.loads(r3.text) 29MsgBody = (json.dumps(Gmail_json['payload']['parts'][0], sort_keys = True, indent = 4)) 30Output = base64.standard_b64decode(MsgBody) 31#print (Output) 32print ("{1}".format(Output, str(Output, encoding='utf-8')))
このコードを実行すると、下記のようなアウトプットがでます。
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-18-8b13705daafb> in <module>()
33 Output = base64.standard_b64decode(MsgBody)
34 # print (Output)
---> 35 print ("{1}".format(Output, str(Output, encoding='utf-8')))
36
37 '''UnicodeDecodeError: 'utf-8' codec can't decode byte 0x87 in position 1: invalid start byte
###試したこと
print (sys.getdefaultencoding()) の結果はUTF-8でした。
特に下記の部分が怪しいと踏んでいるんですが、どのようにすべきかわかりません。
python
1Output = base64.standard_b64decode(MsgBody) 2print ("{1}".format(Output, str(Output, encoding='utf-8')))
34行目の print (Output) をコメントアウトして出力すると、以下の様な出力があります。
b'n\x87ru\xabZtest\r\n---------- Forwarded message ----------\r\nFrom: \xe3\x83\x80\xe3\x82\xa4\xe3\x83\xa4\xe3\x83\xa2\xe3\x83\xb3\xe3\x83\x89\xe3\x83\xbb\xe3\x82\xaa\xe3\x83\xb3\xe3\x83\xa9\xe3\x82\xa4\xe3\x83\xb3 mail-info@diamond.co.jp\r\nDate: 2016-08-02 14:32 GMT-07:00\r\nSubject: \xe3\x83\x84\xe0\xa88+\xae88\x8e\x0e\xf3\x9ab\x83\x9eR\xe3\x82\x92\xe5\xa4\x89\xe3\x81\x88\xe3\x81
どのようにDecode処理をすればよいのか教えて下さい。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。