问题描述
好吧,这是一个非常奇怪的问题。所以我有一个程序,它是这样工作的:
- 用户通过电子邮件将歌曲名称发送至 -------@gmail.com
- 当 -------@gmail.com 阅读电子邮件 (IMAP) 时,它会在天才 (Selenium) 上搜索歌曲
- --------@gmail.com 向原始用户发回有关这首歌的精彩信息/歌词。
我的问题是在第 2 步;阅读电子邮件时,它有时会在字符串中,例如“世界是你的”,有时则是 格式。有时它有 html 标签,有时它没有。我有代码来操作字符串,当它有原始的 html 标签时,但是当它随机进入原始格式时它会搞砸。我使用了一些我在网上找到的代码并对其进行了修改,因为我对 IMAP 不是最好的,但这是我的程序的一部分,可以找到最近发送给它的电子邮件的歌曲名称。
imap = imaplib.IMAP4_SSL("imap.gmail.com")
# authenticate
imap.login(username,password)
status,messages = imap.select("INBox")
# number of top emails to fetch
N = 1
# total number of emails
messages = int(messages[0])
for i in range(messages,messages-N,-1):
# fetch the email message by ID
res,msg = imap.fetch(str(i),"(RFC822)")
for response in msg:
if isinstance(response,tuple):
# parse a bytes email into a message object
msg = email.message_from_bytes(response[1])
# decode the email subject
subject,encoding = decode_header(msg["Subject"])[0]
if isinstance(subject,bytes):
# if it's a bytes,decode to str
subject = subject.decode(encoding)
# decode email sender
From,encoding = decode_header(msg.get("From"))[0]
if isinstance(From,bytes):
From = From.decode(encoding)
print("Subject:",subject)
print("From:",From)
# if the email message is multipart
if msg.is_multipart():
# iterate over email parts
for part in msg.walk():
# extract content type of email
content_type = part.get_content_type()
content_disposition = str(part.get("Content-disposition"))
try:
# get the email body
body = part.get_payload()#(decode=True).decode()
except:
pass
if content_type == "text/plain" and "attachment" not in content_disposition:
# print text/plain emails and skip attachments
print(body)
else:
pass
else:
# extract content type of email
content_type = msg.get_content_type()
# get the email body
body = msg.get_payload(decode=True).decode()
if content_type == "text/plain":
# print only text email parts
print(body)
# close the connection and logout
imap.close()
imap.logout()
body 是用于歌曲名称的变量 感谢您提供任何帮助,如果有更简单的方法来获取最新的电子邮件,请随时告诉我。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)