我使用以下命令从 Gmail 中提取电子邮件:
def getMsgs():
try:
conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
except:
print 'Failed to connect'
print 'Is your internet connection working?'
sys.exit()
try:
conn.login(username, password)
except:
print 'Failed to login'
print 'Is the username and password correct?'
sys.exit()
conn.select('Inbox')
# typ, data = conn.search(None, '(UNSEEN SUBJECT "%s")' % subject)
typ, data = conn.search(None, '(SUBJECT "%s")' % subject)
for num in data[0].split():
typ, data = conn.fetch(num, '(RFC822)')
msg = email.message_from_string(data[0][1])
yield walkMsg(msg)
def walkMsg(msg):
for part in msg.walk():
if part.get_content_type() != "text/plain":
continue
return part.get_payload()
然而,我收到的一些电子邮件几乎不可能从与编码相关的字符(例如“=”)中提取日期(使用正则表达式),这些字符随机落在各个文本字段的中间。这是一个出现在我想要提取的日期范围内的示例:
姓名: KIRSTI 电子邮件:[电子邮件受保护]电话号码:+999
99995192 队伍总数: 4 总数, 0
儿童抵达/出发:10 月 9 日=
,
2010年 - 2010年10月13日 - 2010年10月13日
有没有办法删除这些编码字符?
您可以/应该使用email.parser例如,解码邮件消息的模块(快速而肮脏的例子!):
from email.parser import FeedParser
f = FeedParser()
f.feed("<insert mail message here, including all headers>")
rootMessage = f.close()
# Now you can access the message and its submessages (if it's multipart)
print rootMessage.is_multipart()
# Or check for errors
print rootMessage.defects
# If it's a multipart message, you can get the first submessage and then its payload
# (i.e. content) like so:
rootMessage.get_payload(0).get_payload(decode=True)
使用“解码”参数Message.get_payload,模块根据其编码自动解码内容(例如,您问题中引用的可打印内容)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)