gpt4 book ai didi

python - 通过 Python Gmail-API 在内容中发送带有双尖括号(打开-关闭)的电子邮件

转载 作者:太空狗 更新时间:2023-10-30 02:45:15 25 4
gpt4 key购买 nike

我想通过 Python 中的 Gmail-API 发送电子邮件,但我不断收到以下错误: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Invalid value for .....">

我尝试更改所有内容并得出结论,当我在电子邮件中包含双开右尖括号('<<' 和'>>')(参见示例) 时会发生错误。我尝试了所有方法将文本解析为其他内容,但我认为问题在于我使用“原始”...但“原始”是 Google 示例显示的唯一方式。

还有其他方法可以通过 gmail-api 发送电子邮件吗?或者,换句话说,我该怎么做才能发送一封在文本中带有尖括号的电子邮件?
谢谢!

我当前的代码如下(来自 Google 的示例代码):

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

from apiclient import errors

(...other code...)
SendMessage(service, "me", CreateMessage("me", sender, "<<NOT OK>> " + action, "TEST!"))
(...other code...)

def SendMessage(service, user_id, message):
"""Send an email message.

Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.

Returns:
Sent Message.
"""
try:
# print message
message = service.users().messages().send(userId=user_id, body=message).execute()
print '<mail> Message SEND (Id: %s' % message['id'] + ')'
return message
except errors.HttpError, error:
print 'An error occurred (SendMessage): %s' % error


def CreateMessage(sender, to, subject, message_text):
"""Create a message for an email.

Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.

Returns:
An object containing a base64 encoded email object.
"""

print "<mail> send to: " + to
print "<mail> subject: " + subject
print "<mail> message: " + message_text

message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.b64encode(message.as_string())}

最佳答案

你需要使用:

base64.urlsafe_b64encode(message.as_string())

使用 url-safe base64 字母表,否则您的“原始”字段中将包含无效字符。看: https://developers.google.com/gmail/api/v1/reference/users/messages/send

关于python - 通过 Python Gmail-API 在内容中发送带有双尖括号(打开-关闭)的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25422988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com