如何用Python转发邮件

2 投票
1 回答
6639 浏览
提问于 2025-04-17 08:32

首先,我想说的是,我知道这个问题已经在 使用python smtplib转发邮件中被问过了。

我发这个和那个问题很相关的内容,是因为我尝试过使用那个问题的答案,试着修改一些东西,搜索了谷歌,折腾了大约5个小时,现在我愿意花更多的时间在这个上面。

-- 我只是觉得你们中的某个人可能有答案 :)

我的问题是这样的,我想把一封邮件从我的Gmail转发到另一个Gmail,尽管我运行了很多Python脚本来尝试这个简单的任务,但我还是搞不定。

这是我正在运行的代码(这是我修改过的版本,参考了其他地方发布的内容):

import smtplib, imaplib, email, string

imap_host = "imap.gmail.com"
imap_port = 993
smtp_host = "smtp.gmail.com"
smtp_port = 587
user = "John.Michael.Dorian.4"
passwd = "mypassword"
msgid = 1
from_addr = "John.Michael.Dorian.4@gmail.com"
to_addr = "myotheremail@gmail.com"


# open IMAP connection and fetch message with id msgid
# store message data in email_data
client = imaplib.IMAP4_SSL(imap_host, imap_port)
client.login(user, passwd)
client.select()
typ, data = client.search(None, 'ALL')
for mail in data[0].split():
    typ, data = client.fetch(msgid, "(RFC822)")
    email_data = data[0][1]
client.close()
client.logout()


# create a Message instance from the email data
message = email.message_from_string(email_data)

# replace headers (could do other processing here)
message.replace_header("From", from_addr)
message.replace_header("To", to_addr)
print message.as_string()

# open authenticated SMTP connection and send message with
# specified envelope from and to addresses
smtp = smtplib.SMTP(smtp_host, smtp_port)
smtp.set_debuglevel(1)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(user, passwd)
smtp.sendmail(from_addr, to_addr, message.as_string()) 
smtp.quit()

SMTP调试返回的信息说一切正常,我知道它在发送,因为我试着把

smtp.sendmail(from_addr, to_addr, message.as_string())

替换成

smtp.sendmail(from_addr, to_addr, 'test')

结果也很好。它能正确打印message.as_string(),但我不知道怎么才能让它转发邮件!

这不一定要用SMTP或IMAP或者这些代码(虽然如果能用就好了),但我真的想弄明白怎么做。

我知道这是可能的,因为我昨天成功做到了,但我当时用的电脑(当然是Windows)崩溃了,文件也没了。

对于那些想知道我为什么不直接设置谷歌自动转发所有邮件的人来说,是因为我想要一个脚本,能够一次性移动大量邮件。

谢谢大家!

1 个回答

1

很可能,原始邮件中的“Received:”头信息让 Gmail 把这封邮件给丢掉了。试着在转发之前把这些信息都删掉。

如果这样还不行,可以把头信息打印出来,然后写代码把那些在新邮件中通常不会出现的头信息都删掉。

不过,为什么要这样转发呢?直接从一个 IMAP 账户拉取邮件,然后推送到另一个 IMAP 账户会简单很多。

其实,你可以使用 Mozilla Thunderbird 来添加这两个账户,然后直接把邮件拖放到另一个账户里。

撰写回答