【问题标题】:How to Read emails from an specific mail only with the Gmail API如何仅使用 Gmail API 阅读来自特定邮件的电子邮件
【发布时间】:2023-02-04 03:59:07
【问题描述】:

所以我是一个新手程序员,对如何创建 API 几乎一无所知,我一直在尝试用 Python 编写一个脚本,让我可以从我的 Gmail 帐户中读取我最近的 10 封邮件,但现在我想这样做它只读取来自特定电子邮件的邮件,我不知道该怎么做

  service = build('gmail', 'v1', credentials=creds)

    #Get Mails
    results = service.users().messages().list(userId='me', labelIds=['INBOX']).execute()
    messages = results.get('messages', [])

    message_count = 10
    for message in messages[:message_count]:
        msg = service.users().messages().get(userId='me', id=message['id']).execute()
        email = (msg['snippet'])
        print(f'{email}\n')

我已经说过了,我是一名新手程序员,所以不知道如何解决这个问题。

【问题讨论】:

    标签: python api gmail-api


    【解决方案1】:

    以下是如何使用 Python 中的 Gmail API 读取来自特定电子邮件地址的电子邮件的示例:

    from google.oauth2.service_account import Credentials
    from googleapiclient.discovery import build
    
    def read_emails_from_specific_email(email_address, service):
        result = service.users().messages().list(userId='me', q=f'from:{email_address}').execute()
        messages = result.get('messages', [])
        for message in messages:
            msg = service.users().messages().get(userId='me', id=message['id']).execute()
            print(f'Subject: {msg["subject"]}')
            print(f'From: {msg["from"]}')
            print(f'Body: {msg["body"]}')
    
    # Use a service account to access the Gmail API
    creds = Credentials.from_service_account_file('path/to/service_account.json', scopes=['https://www.googleapis.com/auth/gmail.readonly'])
    service = build('gmail', 'v1', credentials=creds)
    
    # Read emails from a specific email address
    read_emails_from_specific_email('example@gmail.com', service)
    

    在此示例中,read_emails_from_specific_email 函数采用两个参数:email_address 和 service。服务参数是 Gmail API 客户端的一个实例,用于与 API 交互。该函数使用 API 检索从指定的 email_address 发送的邮件列表,然后遍历邮件以打印其主题、发件人和正文。

    在调用该函数之前,代码使用服务帐户获取授权令牌,该令牌用于访问 Gmail API。服务帐户凭据存储在一个 JSON 文件中,该文件被传递给 Credentials.from_service_account_file 方法。 scopes 参数指定应用程序需要访问的 Gmail API 范围。

    最后,调用 read_emails_from_specific_email 函数,将要搜索的电子邮件地址和服务实例作为参数传递。

    【讨论】:

      猜你喜欢
      • 2022-08-17
      • 2018-05-11
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 2020-07-21
      • 2015-09-15
      相关资源
      最近更新 更多