python - 如何在解析时使用 gmail api 将邮件标记为已读?

标签 python gmail-api

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

需要帮助!

最佳答案

您需要modify单独请求中的消息,并删除 UNREAD 标签。

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

{
 "removeLabelIds": [
  "UNREAD"
 ]
}

关于python - 如何在解析时使用 gmail api 将邮件标记为已读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35778772/

相关文章:

Python 过滤器() 函数

Python子进程CREATE_NEW_CONSOLE Windows在kill()时未关闭

ruby-on-rails - rails : Send email using Gmail API with attachment return only encoded file not

gmail - Gmail 邮件 ID 或 ThreadId 如何映射到新的 Gmail 用户界面?

gmail-api - 使用 GMail API 静音

python - 在 python 列表上使用 apply 时出现错误

python - 如何使用 python 将带符号的整数打印为二进制补码的十六进制数?

python - Pandas 'bool object is not callable'

javascript - 我如何从电子邮件中检索他们的时间戳

google-api - 比 yyyy/mm/dd 更精确地列出消息