簡體   English   中英

如何在解析時使用 gmail api 將郵件標記為已讀?

[英]How to mark messages as read using gmail api as i parse?

在 python 中,我如何在從 gmail api 解析消息時將消息標記為“已讀”? 另外我如何在解析后將值保存到數據庫中? 到目前為止,這是獲取每條消息內容的代碼。

from __future__ import print_function
import httplib2
import os
import re
import MySQLdb
from email.utils import parsedate_tz,mktime_tz,formatdate
from requests.adapters import HTTPAdapter
import datetime
from datetime import date,timedelta
import time
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
import json
try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
CLIENT_SECRET_FILE = 'client_server.json'
APPLICATION_NAME = 'Gmail API Python Quickstart'
def get_credentials():

    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 main():

    da=date.fromordinal(730920)
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    today=date.today()
    print (today)
    yesterday=today-timedelta(1)
    print (yesterday) 
    response = service.users().messages().list(userId='me',q='in:inbox is:unread newer_than:1d').execute()
    messages=[]
    store=[]
    message1=[]
    test2=[]
    da=[]
    if 'messages' in response:
     messages.extend(response['messages'])
    fo = open("fooa.txt", "wb") 
    for i in range(len(messages)):
     store=messages[i]['id']
     message = service.users().messages().get(userId='me',id=store,format='metadata',metadataHeaders=['from','date']).execute()
     fo.write(message['snippet'].encode('utf-8')+"")
     From=message['payload']['headers'][0]['value']
     fo.write(From+"");
     da=message['payload']['headers'][1]['value']
     fo.write(da+"\n");
     for line in open("fooa.txt"):
      print(line)
    fo.close()
    a=open("fooa.txt","r")
    for wo in a:
     match=re.findall(r':[\w]+',wo)
     for word in match:
      print(word.replace(':',' '))
    db = MySQLdb.connect("localhost","testuser","mysql23","db1" )
    cursor = db.cursor()
   sql = """INSERT INTO customers((LeadName, CITY, SERVICE,CUSTOMER, MOBILE, EMAIL)
         VALUES (, , , , )"""
try:
   cursor.execute(sql)
   db.commit()
except:
   db.rollback()
    db.close()
if __name__ == '__main__':
    main()

需要幫助請!

您需要在單獨的請求中修改消息,並刪除UNREAD標簽。

POST https://www.googleapis.com/gmail/v1/users/me/messages/1533cb4d7dac1633/modify?access_token={ACCESS_TOKEN}

{
 "removeLabelIds": [
  "UNREAD"
 ]
}

如果您嘗試將消息標記為已讀,則必須執行以下操作:

gmail_service
       .users()
       .messages()
       .modify(userId='me', id=message_id, body={'removeLabelIds': ['UNREAD']})
       .execute()

您可以使用 Gmail API 做什么取決於您授予 OAuth 的范圍。 您需要執行以下操作:

  1. SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'更改為:
SCOPES = [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/gmail.modify'
]

說明:由於將電子郵件標記為“未讀”是一種消息修改,因此您需要“gmail.modify”范圍才能使用此 API 請求。 要查看范圍的完整列表,請參閱選擇身份驗證范圍

  1. 刪除您的token.pickle文件並重新運行腳本。 您需要執行此操作才能使用新范圍重新授權 OAuth 應用程序,然后將生成新的token.pickle文件。

  2. 這是在 Python 中將電子郵件標記為已讀的代碼:

service.users().messages().modify(userId='me', id=message['id'], body={
    'removeLabelIds': ['UNREAD']
}).execute()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM