如何使用 uid 打印单个电子邮件的主题
How to print the subject of a single email using uid
我正在使用 python 2.7 imap 库打印一封电子邮件的主题,我已经拥有其 UID。这很简单,我是 Python 的新手,只是在使用库时遇到了问题。
这是我的:
# Retrieve and store ID & UID for most recent email received
result, data = mail.search(None,'ALL') # search and return sequential ids
latest_id = data[0].split()[-1]
result, data = mail.uid('search', None, "ALL") # search and return uids instead
latest_uid = data[0].split()[-1]
现在我只想打印由 latest_uid
标识的电子邮件的主题。
感谢您的帮助!
我获取主题的方法是使用 RFC 822(电子邮件标准格式)获取整个消息数据,然后使用电子邮件将其转换为 python 电子邮件 object模块。
使用 RFC 822 将获取整封邮件,但如果您只需要主题,您可以只获取 header(在下面注释掉)。如果您决定只获取 header,只需解析以 Subject:
开头的行。
imaplib 文档 https://pymotw.com/2/imaplib/ 更深入地介绍了以下代码中发生的事情。
import email, imaplib
# typ, msg_data = c.fetch('1', '(BODY.PEEK[HEADER])')
t, d = mail.fetch(latest_uid, '(RFC822)')
for res_part in d:
if isinstance(res_part, tuple):
msg = email.message_from_string(res_part[1])
subject = msg['subject']
我正在使用 python 2.7 imap 库打印一封电子邮件的主题,我已经拥有其 UID。这很简单,我是 Python 的新手,只是在使用库时遇到了问题。
这是我的:
# Retrieve and store ID & UID for most recent email received
result, data = mail.search(None,'ALL') # search and return sequential ids
latest_id = data[0].split()[-1]
result, data = mail.uid('search', None, "ALL") # search and return uids instead
latest_uid = data[0].split()[-1]
现在我只想打印由 latest_uid
标识的电子邮件的主题。
感谢您的帮助!
我获取主题的方法是使用 RFC 822(电子邮件标准格式)获取整个消息数据,然后使用电子邮件将其转换为 python 电子邮件 object模块。
使用 RFC 822 将获取整封邮件,但如果您只需要主题,您可以只获取 header(在下面注释掉)。如果您决定只获取 header,只需解析以 Subject:
开头的行。
imaplib 文档 https://pymotw.com/2/imaplib/ 更深入地介绍了以下代码中发生的事情。
import email, imaplib
# typ, msg_data = c.fetch('1', '(BODY.PEEK[HEADER])')
t, d = mail.fetch(latest_uid, '(RFC822)')
for res_part in d:
if isinstance(res_part, tuple):
msg = email.message_from_string(res_part[1])
subject = msg['subject']