首页 > 解决方案 > 如何在 Python 中使用 Gmail API 仅获取最新的电子邮件

问题描述

每当我的收件箱中有新电子邮件时,我将如何编写 Python 脚本来工作。Gmail Python SDK 中是否有任何特殊工具可以轻松完成此操作,而不是使用 MAPI 并每天检查新的收件箱更新?

标签: python

解决方案


你可以使用这样的东西。

def get_email():
    #credentials
    username ="youremail@gmail.com"
    #generated app password
    app_password= "emailPasswd"
    # https://www.systoolsgroup.com/imap/
    gmail_host= 'imap.gmail.com'
    #set connection
    mail = imaplib.IMAP4_SSL(gmail_host)
    #login
    mail.login(username, app_password)
    #select inbox
    mail.select("INBOX")
    time.sleep(1)
    #select specific mails
    _, selected_mails = mail.search(None,"UNSEEN", '(FROM "specificUser@gmail.com")') # get emails only from specific sender
    #total number of mails from specific user
    for num in selected_mails[0].split():
        your_function() # call your function here so for every new mail this will run
        _, data = mail.fetch(num , '(RFC822)')
        _, bytes_data = data[0]
        #access data
        subject_of_mail = email_message["subject"] 
            for part in email_message.walk():
                if part.get_content_type()=="text/plain" or part.get_content_type()=="text/html":
                    message = part.get_payload(decode=True)
        else:
            pass

schedule.every(5).seconds.do(get_email)

#other schedule options
"""
schedule.every(10).minutes.do(get_email)
schedule.every().hour.do(get_email)
schedule.every().day.at("10:30").do(get_email)
schedule.every(5).to(10).minutes.do(get_email)
schedule.every().monday.do(get_email)
schedule.every().wednesday.at("13:15").do(get_email)
schedule.every().minute.at(":17").do(get_email)
"""
while True:
    schedule.run_pending()
    time.sleep(1)

推荐阅读