我使用以下方法从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()
然而,我得到的一些电子邮件几乎不可能从编码相关字符(如‘=’)中提取日期(使用正则表达式),在各种文本字段的中间随机地出现。下面是一个示例,它发生在我要提取的日期范围内:Name: KIRSTI Email: kirsti@blah.blah Phone #: + 999 99995192 Total in party: 4 total, 0 children Arrival/Departure: Oct 9= , 2010 - Oct 13, 2010 - Oct 13, 2010
有没有办法删除这些编码字符
这就是所谓的引用可打印编码。您可能想要使用类似
quopri.decodestring
-http://docs.python.org/library/quopri.html的东西如果您使用的是Python3.6或更高版本,则可以使用^{} 方法自动解码文本。此方法取代了
get_payload()
,尽管get_payload()
仍然可用假设您有一个包含此电子邮件的字符串
s
(基于文档中的examples):字符串中的非ascii字符已使用
quoted-printable
编码进行编码,如Content-Transfer-Encoding
头中所指定创建电子邮件对象:
此处需要设置策略;否则使用^{} ,返回一个没有get_content方法的遗留消息实例^{} 最终将成为默认策略,但从Python3.7开始,它仍然是
policy.compat32
get_content()
方法自动处理解码:如果您有一条多部分消息,则需要对各个部分调用
get_content()
,如下所示:例如,您可以/应该使用^{} 模块对邮件消息进行解码(快速和肮脏的示例!):
使用^{} 的“decode”参数,模块根据其编码(例如,如您问题中引用的可打印内容)自动解码内容
相关问题 更多 >
编程相关推荐