gpt4 book ai didi

python imaplib 读取gmail

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:42 25 4
gpt4 key购买 nike

我正在使用 imaplib 在我的 python 命令窗口中读取 gmail 邮件。唯一的问题是电子邮件是否带有换行符和回车符。此外,文本的格式似乎不正确。它返回的不是金额:36.49 美元,而是 =2436.49。我怎样才能清理这段文字?谢谢!

示例电子邮件内容:

r\nItem name: Scanner\r\nItem=23: 130585100869\r\nPurchase Date: Oct 7, 2011\r\nUnit Price: =2436.49 USD\r\nQty: 1\r\nAmount: =2436.49USD\r\nSubtotal: =2436.49 USD\r\nShipping and handling: =240.00 USD\r\nInsurance - not offered

代码:

import imaplib
import libgmail
import re
import email
from BeautifulSoup import BeautifulSoup

USER = 'email@gmail.com'
PASSWORD = 'password'

#connecting to the gmail imap server
imap_server = imaplib.IMAP4_SSL('imap.gmail.com', 993)
imap_server.login(USER, PASSWORD)
imap_server.select('Inbox')

typ, response = imap_server.search(None, '(SUBJECT "payment received")')

Data = []

for i in response[0].split():
results, data = imap_server.fetch(i, "(RFC822)")
Data.append(data)
break

for i in Data:
print i

最佳答案

数据采用可引用打印编码,这是一个小型数据按摩器,可以满足您的需求:

text = '''\r\nPurchase Date: Oct 7, 2011\r\nUnit Price: =2436.49 USD\r\nQty: 1\r\nAmount: =2436.49 USD\r\nSubtotal: =2436.49 USD\r\nShipping and handling: =240.00 USD\r\nInsurance - not offered : ----\r\n----------------------------------------------------------------------\r\nTax: --\r\nTotal: =2436.49 USD\r\nPayment: =2436.49 USD\r\nPayment sent to: emailaddress=40gmail.com\r\n----------------------------------------------------------------------\r\n\r\nSincerely,\r\nPayPal\r\n=20\r\n----------------------------------------------------------------------\r\nHelp Center:=20\r\nhttps://www.paypal.com/us/cgi-bin/helpweb?cmd=3D_help\r\nSecurity Center:=20\r\nhttps://www.paypal.com/us/security\r\n\r\nThis email was sent by an automated system, so if you reply, nobody will =\r\nsee it. To get in touch with us, log in to your account and click =\r\n=22Contact Us=22 at the bottom of any page.\r\n\r\n'''

raw_data = text.decode("quopri") #replace =XX for the real characters

data = [map(str.strip, l.split(":")) for l in raw_data.splitlines() if ": " in l]

print data
# [['Purchase Date', 'Oct 7, 2011'], ['Unit Price', '$36.49 USD'], ['Qty', '1'], ['Amount', '$36.49 USD'], ['Subtotal', '$36.49 USD'], ['Shipping and handling', '$0.00 USD'], ['Insurance - not offered', '----'], ['Tax', '--'], ['Total', '$36.49 USD'], ['Payment', '$36.49 USD'], ['Payment sent to', 'emailaddress@gmail.com'], ['Help Center', ''], ['Security Center', '']]

您的数据格式更易于处理,希望对您有所帮助。

编辑:让它更可爱:

>>> cooked = dict(data)
>>> print cooked["Unit Price"]
$36.49 USD

关于python imaplib 读取gmail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9385979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com