[英]Gmail api python encode/decode error
我有問題。 我正在嘗試使用 gmail api 從 gmail 讀取電子郵件。 我按照這里的說明https://developers.google.com/gmail/api/v1/reference/users/messages/get
我做了一些更改以在 python 3 上運行它,所以我最終得到了以下代碼:
def GetMimeMessage(service, user_id, msg_id):
try:
message = service.users().messages().get(userId=user_id, id=msg_id,
format='raw').execute()
print ('Message snippet: %s' % message['snippet'])
msg_str = base64.urlsafe_b64decode(message['raw'].encode('utf8'))
mime_msg = email.message_from_bytes(msg_str)
print(mime_msg)
return mime_msg
except errors.HttpError as error:
print ('An error occurred: %s' % error)
現在輸出非常接近我想要的,但有一個問題是輸出中的匈牙利重音字符很奇怪: G=C3=A1bor
而不是Gábor
而且 html 標簽也被破壞了:
Follow us: =09=09=09=09=09=09=09=09=09<a href=3D"http=
我已經發現這與消息的編碼方式有關,請參閱電子郵件的標題:
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
問題是,我似乎找不到正確解碼它的方法。 永遠的幫助表示贊賞。
經過幾個小時的苦苦掙扎,我終於找到了解決方案(至少對我而言)。 即使通過線程是舊的,我將它張貼在這里,以便其他人以后可以找到它。 它是這樣的:
# Get your message
message = service.users().messages().get(userId=user_id, id=msg_id, format='full').execute()
# Get the right body data item (this part was my Heureka-moment as there are several 'data' keys)
content = message['payload']['parts'][0]['parts'][1]['body']['data']
# Encode
msg_body = base64.urlsafe_b64decode(content).decode('utf-8')
這個序列使解碼/編碼對我有用。 關於 base64 和 Google Gmail API 的解碼/編碼問題,有許多不同的解決方案建議,但似乎每種情況都是獨一無二的。 希望這個解決方案也能幫到你!
謝謝圖皮塔皮。 Python 的 Gmail API 文檔可能更清楚一些。 上述解決方案也適用於我。 我可以通過以下方式檢索內容:
msgs = message['payload']['parts']
msg = msgs[1]['body']['data']
MessagePart 可能由不同的部分組成:
"parts": [
{
"partId": "0",
"mimeType": "text/plain",
"filename": "",
"headers": [
{ "name": "Content-type", "value": "text/plain;charset=utf-8" },
{ "name": "Content-Transfer-Encoding", "value": "quoted-printable" }
],
"body": {
"size": 1887,
"data": "ascii string to be decoded"
}
},
{
"partId": "1",
"mimeType": "text/html",
"filename": "",
"headers": [
{ "name": "Content-type", "value": "text/html;charset=utf-8" },
{ "name": "Content-Transfer-Encoding", "value": "quoted-printable" }
],
"body": {
"size": 66970,
"data": "longer ascii string to be decoded"
}
}
]
從文檔中提取完整的有效負載:
Resource representations An email message.
{ "id": string, "threadId": string, "labelIds": [
string ], "snippet": string, "historyId": unsigned long, "internalDate": long, "payload": {
"partId": string,
"mimeType": string,
"filename": string,
"headers": [
{
"name": string,
"value": string
}
],
"body": users.messages.attachments Resource,
"parts": [
(MessagePart)
] }, "sizeEstimate": integer, "raw": bytes }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.