【发布时间】:2021-04-17 21:19:02
【问题描述】:
我正在编写一个机器人,我正在使用 python 中的 imaplib 从 gmail 获取电子邮件并从中输出一些有用的数据。不过,我在选择收件箱时遇到了麻烦。现有的分拣系统使用自定义标签来区分来自不同客户的电子邮件。我在我的测试电子邮件中部分复制了这个系统,但 imaplib.select() 使用自定义标签抛出“imaplib.IMAP4.error: SELECT command error: BAD [b'Could not parse command']”。 Screenshot attatched我的机器人对默认的 gmail 文件夹没有问题,可以获取收件箱或 [Gmail]/垃圾邮件。在这种情况下,它会命中error later in the code that deals with completely different problem I have yet to fix。不过,重点是 imaplib.select() 在默认收件箱中是成功的,而不是自定义标签。
我的代码的工作方式是它通过所有可用的收件箱工作,将其与用户输入的名称进行比较,如果它们匹配,则保存名称并将布尔值设置为 true 以表示它找到了匹配项。然后它检查是否存在匹配项(用户输入的收件箱存在),否则它会抛出错误消息并重置。然后它会尝试选择用户输入的收件箱。
我已验证程序保存收件箱名称的变量是否与 imap.list() 命令中列出的名称相匹配。我不知道问题是什么。
我可以通过遍历所有邮件来查找我正在寻找的电子邮件来绕过该过程,但是由于我将使用的帐户中的电子邮件数量庞大,使用现有的分类系统效率更高。
感谢任何帮助!
编辑:请求后附加代码。感谢告诉我这样做的人。
'''
Fetches emails from the specified inbox and outputs them to a popup
'''
def fetchEmails(self):
#create an imap object. Must be local otherwise we can only establish a single connection
#imap states are kinda bad
imap = imaplib.IMAP4_SSL(host="imap.gmail.com", port="993")
#Login and fetch a list of available inboxes
imap.login(username.get(), password.get())
type, inboxList = imap.list()
#Set a reference boolean and iterate through the list
inboxNameExists = False
for i in inboxList:
#Finds the name of the inbox
name = self.inboxNameParser(i.decode())
#If the given inbox name is encountered, set its existence to true and break
if name.casefold().__eq__(inboxName.get().casefold()):
inboxNameExists = True
break
#If the inbox name does not exist, break and give error message
if inboxNameExists != True:
self.logout(imap)
tk.messagebox.showerror("Disconnected!", "That Inbox does not exist.")
return
'''
If/else to correctly feed the imap.select() method the inbox name
Apparently inboxes containing spaces require quoations before and after
Selects the inbox and pushes it to a variable
two actually but the first is unnecessary(?)
imap is weird
'''
if(name.count(" ") > 0):
status, messages = imap.select("\"" + name + "\"")
else:
status, messages = imap.select(name);
#Int containing total number of emails in inbox
messages = int(messages[0])
#If there are no messages disconnect and show an infobox
if messages == 0:
self.logout(imap)
tk.messagebox.showinfo("Disconnected!", "The inbox is empty.")
self.mailboxLoop(imap, messages)
在与朋友讨论了几个小时后解决了这个问题。事实证明,问题在于 imap.select() 如果邮箱名称包含空格,则需要在邮箱名称周围加上引号。所以 imap.select("INBOX") 很好,但是有空格你需要 imap.select("\"" + "Label Name" + "\"")
你可以在我发布的最后一个 if/else 语句的代码中看到这一点。
【问题讨论】:
-
请在问题中包含代码。 (SO 上不接受文字照片;人们应该能够搜索代码和错误消息并获得结果,明白吗?)
标签: python email gmail imap imaplib