用Python阅读Gmail电子邮件 [英] Reading Gmail Email in Python
问题描述
我正在尝试创建一个简单的脚本来检查我的Gmail中是否有具有特定标题的电子邮件.当我在Python 3.7.3上运行该程序时,收到以下数据:('OK',[b'17'])
.
I am attempting to create a simple script to check my Gmail for emails with a certain title. When I run this program on Python 3.7.3 I receive this data: ('OK', [b'17'])
.
我需要在python中访问电子邮件的正文.我只是不确定该如何处理我拥有的数据.
I need to access the body of the email within python. I am just not sure what to do with the data that I have.
这是我当前的代码:
import imaplib
import credentials
imap_ssl_host = 'imap.gmail.com'
imap_ssl_port = 993
username = credentials.email
password = credentials.passwd
server = imaplib.IMAP4_SSL(imap_ssl_host, imap_ssl_port)
server.login(username, password)
server.select('INBOX')
data = server.uid('search',None, '(SUBJECT "MY QUERY HERE!")')
print(data)
运行代码的结果:
('OK', [b'17'])
我知道这有点粗糙,但是我仍在学习,因此,如果您有任何帮助我改善的建议,将不胜感激!
I know it is a little rough, but I am still learning, so any advice you have to help me improve would be greatly appreciated!
推荐答案
您需要首先列出所选邮箱的内容,并获取其中一项.您可以执行以下操作(也可以查看@asynts建议的链接)
You need to first list the contents of the selected mailbox and fetch one of the items. You could do something like this (also check the link suggested by @asynts)
imap.select('Inbox')
status, data = imap.search(None, 'ALL')
for num in data[0].split():
status, data = imap.fetch(num, '(RFC822)')
email_msg = data[0][1]
如果只需要正文中的特定字段,而不是解析RFC,则可以过滤以下字段:
If you only want specific fields in the body, instead of parsing the RFC you could filter fields like:
status, data = imap.fetch(num, '(BODY[HEADER.FIELDS (SUBJECT DATE FROM TO)])')
这篇关于用Python阅读Gmail电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!