使用python发送消息时出现错误400

2024-04-05

我正在尝试使用 Gmail API 发送电子邮件。我已成功通过身份验证,并且我的计算机上有一个 client_secret.json 文件。 我已经能够使用 Gmail API 网站上的快速入门示例获取标签列表

我已成功将范围重置为

SCOPES = 'https://mail.google.com'

允许完全访问我的 Gmail 帐户。

我有一个 python 脚本,编译自here https://developers.google.com/gmail/api/quickstart/python#step_3_set_up_the_sample and here https://developers.google.com/gmail/api/guides/sending#sending_messages。见下文。执行脚本时,我收到以下错误消息:

发生错误:https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json 返回“'原始'RFC822 有效负载消息字符串或通过 /upload/* 需要 URL 上传消息”>

关于我做错了什么以及如何解决它有什么想法吗?

from __future__ import print_function
import argparse
import time
from time import strftime, localtime
import os

import base64
import os
import httplib2
from httplib2 import Http

from apiclient import errors
from apiclient import discovery

import oauth2client
from oauth2client import file, client, tools

SCOPES = 'https://mail.google.com'
CLIENT_SECRET_FILE = 'client_secret.json'
store = file.Storage('storage.json')
credentials = store.get()
if not credentials or credentials.invalid:
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    credentials = tools.run_flow(flow, store, flags)

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
        'gmail-python-quickstart.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials


def send_message(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:
      message = (service.users().messages().send(userId=user_id, body=message)
                 .execute())
      print ('Message Id: %s' % message['id'])
      return message
  except errors.HttpError, error:
      print ('An error occurred: %s' % error)


def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    send_message(service, 'me','test message')


main()

必须像中概述的那样创建一条消息发送电子邮件 https://developers.google.com/gmail/api/guides/sending#creating_messages guide:

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

def main():
  credentials = get_credentials()
  http = credentials.authorize(httplib2.Http())
  service = discovery.build('gmail', 'v1', http=http)
  message = create_message(
    '[email protected] /cdn-cgi/l/email-protection', '[email protected] /cdn-cgi/l/email-protection', 'Subject', 'Message text'
  )
  send_message(service, 'me', message)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用python发送消息时出现错误400 的相关文章

随机推荐

  • 设置 dplyr 链内列的格式

    我有这个数据集 dat lt structure list date structure c 1L 1L 1L 2L 2L 2L 3L 3L 3L 4L 4L Label c 3 31 2014 4 1 2014 4 2 2014 4 3
  • 如何让Android KitKat用户不下载应用程序?

    我在Android 中开发了一个应用程序 它适用于除 KitKat 用户之外的所有用户 当我在 Play 商店上传此应用程序时 我希望 KitKat 用户无法下载此应用程序 即使当我在系统中执行此应用程序时 它也会检测 KitKat 手机
  • 在java中创建自定义对象数组

    我有 100 条数据记录 这些数据是从服务传入我的系统的 我想为每条记录创建 100 个类对象 以便将其序列化为我的自定义类 我在 for 循环内进行内存创建 如下所示 for int i 0 i lt 100 i SomeClass s1
  • 将 HTML 文件解析为 PHP

    这是将 html 文件解析为 php 的正确方法吗 RemoveHandler html htm AddType application x httpd php php htm html 保存在根文件夹中的 htaccess 文件中吗 我添
  • NSApplication windows 属性 - windows 未删除?

    我有一个显示模式的 NSWindow Controller 它有一个 关闭 按钮 连接到如下操作 IBAction close id sender self window orderOut sender self window close
  • 在多个线程中重用 Tensorflow 会话会导致崩溃

    背景 我有一些复杂的强化学习算法 我想在多个线程中运行 Problem 当尝试打电话时sess run在一个线程中我收到以下错误消息 RuntimeError The Session graph is empty Add operation
  • 为什么渲染属性会多次调用 getter?

    与前面的示例相关 我尝试监视服务器上的 get set 方法 调用它们的时间以及调用频率 所以 我的实际情况是这样的 ManagedBean name selector RequestScoped public class Selector
  • 为什么 HSQLDialect 初始化在 Spring Boot 项目中需要这么长时间?

    我编写了一个 Spring Boot REST api 它连接到具有大量表的旧版 MySQL 数据库 10759 当我启动 Spring Boot 项目时 日志停在一行 表明 HSQLDialect 正在初始化 日志需要几分钟才能恢复工作
  • Terraform:将整个资源组移动到新的 Azure 订阅

    历史上增长的项目及其在 Azure 上的相关基础设施必须进行拆分 幸运的是 它的结构良好 因此很明显我们需要将两个资源组及其附属资源移动到新的 Azure 订阅 我查过了 大部分资源可以移动 https learn microsoft co
  • 在打字稿中导入模块时,绝对路径的根是什么?

    我正在使用打字稿 在 Visual Studio 2015 中 开发一个应用程序 并具有以下基本文件结构 Solution AppProject Scripts framework Utils ts app SomeApp ts tscon
  • 通过socks的Python ssh客户端(代理)

    所以 我需要通过代理socks连接到SSH服务器 我阅读了 paramiko 和twisted conch 文档 但没有在那里找到代理袜子支持 这个套接字包装器允许您使用静态 ssh 隧道 我找到了解决我的问题的通用方法 使用帕里科SSHC
  • OCaml 在运行时编译和加载

    我正在尝试实现类似的目标eval 在 OCaml 中 我有一个string我想从中得到一个 OCaml 函数 目前我正在做以下事情 我将字符串转储到new ml并编译文件 Compile implementation Format std
  • JavaScript AJAX 远程记录器 [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在平台上开发 JavaScript 应用程序 该平台不支持日志输出 不允许为记录器输出打开新窗口
  • Swift 使用 UnsafePointer 从 UnsafeMutablePointer 获取值

    我正在努力通过contextInfo of typeUnsafeMutablePointer
  • 如何将异常保存在txt文件中?

    public DataTable InsertItemDetails FeedRetailPL objFeedRetPL DataTable GetListID new DataTable try SqlParameter arParams
  • 如何知道 Mongoose 的 upsert 是否创建了新文档?

    我在 node js express js 中有这段代码 var User mongoose model User var usersRouter express Router usersRouter put id function req
  • 升级AGP版本失败

    我无法更新我的项目 当我尝试这样做时 我收到了这条消息 升级助手无法升级此项目 找不到执行将 AGP 版本从 4 1 3 升级到 4 2 0 命令的方法 可能是因为该项目的构建文件使用了升级助手当前不支持的功能 例如 使用定义的常量 在 b
  • 如何在 Treeview 控件中使子节点可见 = false

    我有一个带有树视图控件的窗口窗体 该树视图有一个根节点和 2 个子节点 我的要求是我需要隐藏第一个子节点 是否有可能使特定孩子点头可见为假 是的 您可以从树节点继承并创建您自己的行为 就像这样 public class RootNode T
  • 使用 Angular 6 和 Spring Rest API 下载文件

    我在使用 Angular 6 从 Rest api 下载文件时遇到问题 后端方法 RequestMapping value print id public ResponseEntity
  • 使用python发送消息时出现错误400

    我正在尝试使用 Gmail API 发送电子邮件 我已成功通过身份验证 并且我的计算机上有一个 client secret json 文件 我已经能够使用 Gmail API 网站上的快速入门示例获取标签列表 我已成功将范围重置为 SCOP