python - 如何在 Python 中使用 Gmail API 仅获取最新的电子邮件
问题描述
每当我的收件箱中有新电子邮件时,我将如何编写 Python 脚本来工作。Gmail Python SDK 中是否有任何特殊工具可以轻松完成此操作,而不是使用 MAPI 并每天检查新的收件箱更新?
解决方案
你可以使用这样的东西。
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)
推荐阅读
- sql - 基于关联对象时间范围的 Rails 范围
- amazon-web-services - 如何找到 aws cli 正在使用的确切配置?
- sql - 在选择中排序以及聚合 - SQL Server
- asp.net - 在asp.net core 5中获取绝对当前请求url
- c# - 使用通用存储库、UnitOfWork、NUnit 和 Moq 进行单元测试
- javascript - 使用 Javascript 将字符串中的多个加号 (+) 替换为单个加号 (+)
- swift - 如何隐藏项目
- javascript - ReactJS - 更新状态会导致延迟
- python - 无法从网页中找到所有 href 链接
- r - 用 NA 替换字符串 'NULL'