2010-10-28 47 views
3

我提取使用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() 

然而,一些电子邮件,我得到的几乎是不可能的,我从中提取日期(使用正则表达式)的编码相关的字符,如'=',随机落在各种文本字段的中间。这里就是它,我想提取发生在日期范围的例子:

名称:基尔斯蒂电子邮件: [email protected]电话号码:+ 999 99995192党总:4总,0 孩子到达/出发时间:10月9日= , 2010 - 2010年10月13日 - 2010年10月13日

有没有办法来消除这些编码的字符?

+0

是的......我认为它把那些有换行符换行的地方。应该是一个lib来正确解码它。 – mpen 2010-10-28 07:13:57

回答

4

你可以/应该使用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,模块根据其编码自动解码内容(例如,在您的问题中引用了printables)。

+0

decode = True当charset是us-ascii时不起作用。 – Ale 2012-11-07 18:47:03