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

跟風遠走 提交于 2021-02-07 03:07:07

问题


In python how do i mark messages as 'read' as i parse it from gmail api ? Also how do i save the values to the database after parsing? This is the code so far to get the content of each message.

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

Need help please!


回答1:


You need to modify the message in a separate request, and remove the UNREAD-label.

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

{
 "removeLabelIds": [
  "UNREAD"
 ]
}



回答2:


If you're trying to mark the message as read, you will have to do something like:

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



回答3:


What you can do with the Gmail API depends on what scope you've granted OAuth. Here's what you need to do:

  1. Change SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' to this:
SCOPES = [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/gmail.modify'
]

Explanation: since marking an email as "unread" is a message modification, you need the 'gmail.modify' scope in order to use this API request. To see the full list of scopes, refer to Choose Auth Scopes.

  1. Delete your token.pickle file and rerun the script. You'll need to do this in order to reauthorize the OAuth app with the new scopes, which will then generate a new token.pickle file.

  2. Here's the code to mark an email as read in Python:

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


来源:https://stackoverflow.com/questions/35778772/how-to-mark-messages-as-read-using-gmail-api-as-i-parse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!