如何阅读Python 3中的电子邮件内容

2024-06-02 11:10:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试了很多代码来访问和读取电子邮件内容,例如,关于Gmail,我只能进行身份验证,使用Outlook,我有可以读取电子邮件的代码,但它是加密的……但现在它只访问电子邮件,不输出加密信息。所以我需要帮助来解决这个问题。谢谢

代码如下:

import imaplib
import base64 

email_user = input('Email: ')
email_pass = input('Password: ')

M = imaplib.IMAP4_SSL('imap-mail.outlook.com', 993)
M.login(email_user, email_pass)
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    num1 = base64.b64decode(num1)
    data1 = base64.b64decode(data)
    print('Message %s\n%s\n' % (num, data[0][1]))
M.close()
M.logout()

Tags: 代码import内容inputdata电子邮件emailpass
2条回答

使用数据[0][1].decode('utf-8')

它会起作用的。我也面临同样的问题。这对我有效。

我已经检查了你的代码,还有一些评论。第一个问题是,当你在这里粘贴代码时,逗号似乎被去掉了。我试过把它们放回去,所以检查我的代码和你的代码是否匹配。请记住,如果没有访问Outlook的权限,我无法测试我的建议。

import imaplib
import base64
email_user = input('Email: ')
email_pass = input('Password: ')

M = imaplib.IMAP4_SSL('imap-mail.outlook.com', 993)
M.login(email_user, email_pass)
M.select()

typ, data = M.search(None, 'ALL')

for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')   # data is being redefined here, that's probably not right
    num1 = base64.b64decode(num1)          # should this be (num) rather than (num1) ?
    data1 = base64.b64decode(data)
    print('Message %s\n%s\n' % (num, data[0][1]))  # don't you want to print num1 and data1 here?

M.close()
M.logout()

假设这是正确重构的,您可以在第10行调用消息列表数据,但随后将调用fetch()的结果重新分配给第13行的数据。

在第14行,你解码了num1,它还没有被定义。但我不确定这些数字是否需要解码,这似乎有点奇怪。

在第16行,打印的是已编码的值,而不是已解码的值。我想你可能想要

import imaplib
import base64
email_user = input('Email: ')
email_pass = input('Password: ')

M = imaplib.IMAP4_SSL('imap-mail.outlook.com', 993)
M.login(email_user, email_pass)
M.select()

typ, message_numbers = M.search(None, 'ALL')  # change variable name, and use new name in for loop

for num in message_numbers[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    # num1 = base64.b64decode(num)          # unnecessary, I think
    print(data)   # check what you've actually got. That will help with the next line
    data1 = base64.b64decode(data[0][1])
    print('Message %s\n%s\n' % (num, data1))

M.close()
M.logout()

希望能有所帮助。

相关问题 更多 >