保存邮件附件(python3,pop3_ssl,gmail)

3 投票
1 回答
11149 浏览
提问于 2025-04-17 07:18

我正在尝试从谷歌邮箱账户保存邮件附件。

据我所知,可以通过“遍历”邮件内容来获取它的有效载荷,

for part in message.walk():
    # getting payload, saving attach etc.

但是这方法并没有成功。

下面是完整的例子:

def test_save_attach(self):
    self.connection = poplib.POP3_SSL('pop.gmail.com', 995)
    self.connection.set_debuglevel(1)
    self.connection.user(USERNAME)
    self.connection.pass_(PASS)

    emails, total_bytes = self.connection.stat()
    print("{0} emails in the inbox, {1} bytes total".format(emails, total_bytes))
    # return in format: (response, ['mesg_num octets', ...], octets)
    msg_list = self.connection.list()
    print(msg_list)

    # messages processing
    for i in range(emails):
        response = self.connection.retr(i+1)
        # return in format: (response, ['line', ...], octets)
        lines = response[1]
        str_message = email.message_from_bytes(b''.join(lines))
        print(str_message)

        # save attach
        for part in str_message.walk():
            print(part.get_content_type())

            if part.get_content_maintype() == 'multipart':
                continue

            if part.get('Content-Disposition') is None:
                continue

            filename = part.get_filename()
            if not(filename): continue

            fp = open(os.path.join(self.savedir, filename), 'wb')
            fp.write(part.get_payload(decode=1))
            fp.close

    self.connection.quit()

脚本的输出结果是:

*cmd* 'USER **********'
*cmd* 'PASS **********'
*cmd* 'STAT'
*stat* [b'+OK', b'1', b'5301']
1 emails in the inbox, 5301 bytes total
*cmd* 'LIST'
(b'+OK 1 messages (5301 bytes)', [b'1 5301'], 8)
*cmd* 'RETR 1'
[<message headers and body>]
text/plain
*cmd* 'QUIT'

从输出结果来看,邮件中只有一部分是'text/plain'格式,并且没有任何附件信息,尽管邮件内容里确实包含了附件信息,而且在调试输出时可以看到。

1 个回答

9
response = self.connection.retr(i+1)
raw_message = response[1]

raw_message 不是一个字符串。retr 方法返回的是一系列单独的行,组成一个列表。你试图用 str(raw_message) 将这个列表转换成字符串,但这样是行不通的。

相反,你应该把这些行连接起来,比如,把

str_message = email.message_from_string(str(raw_message))

替换成:

python2:

str_message = email.message_from_string("\n".join(raw_message))

python3:

str_message = email.message_from_bytes(b'\n'.join(raw_message))

编辑:我会添加我完整的工作源代码和输出,以帮助调试这个问题

import poplib
import email
import os

class GmailTest(object):
    def __init__(self):
        self.savedir="/tmp"

    def test_save_attach(self):
        self.connection = poplib.POP3_SSL('pop.gmail.com', 995)
        self.connection.set_debuglevel(1)
        self.connection.user("<munged>")
        self.connection.pass_("<munged>")

        emails, total_bytes = self.connection.stat()
        print("{0} emails in the inbox, {1} bytes total".format(emails, total_bytes))
        # return in format: (response, ['mesg_num octets', ...], octets)
        msg_list = self.connection.list()
        print(msg_list)

        # messages processing
        for i in range(emails):

            # return in format: (response, ['line', ...], octets)
            response = self.connection.retr(i+1)
            raw_message = response[1]

            str_message = email.message_from_bytes(b'\n'.join(raw_message))

            # save attach
            for part in str_message.walk():
                print(part.get_content_type())

                if part.get_content_maintype() == 'multipart':
                    continue

                if part.get('Content-Disposition') is None:
                    print("no content dispo")
                    continue

                filename = part.get_filename()
                if not(filename): filename = "test.txt"
                print(filename)

                fp = open(os.path.join(self.savedir, filename), 'wb')
                fp.write(part.get_payload(decode=1))
                fp.close

        #I  exit here instead of pop3lib quit to make sure the message doesn't get removed in gmail
        import sys
        sys.exit(0)

d=GmailTest()
d.test_save_attach()

输出:

python3 thetest.py
*cmd* 'USER <munged>'
*cmd* 'PASS <munged>'
*cmd* 'STAT'
*stat* [b'+OK', b'2', b'152928']
2 emails in the inbox, 152928 bytes total
*cmd* 'LIST'
(b'+OK 2 messages (152928 bytes)', [b'1 76469', b'2 76459'], 18)
*cmd* 'RETR 1'
multipart/mixed
text/plain
test.txt
application/pdf
ADDFILE_0.pdf
*cmd* 'RETR 2'
multipart/mixed
text/plain
test.txt
application/pdf
ADDFILE_0.pdf

撰写回答