繁体   English   中英

如何使用 Python 转发电子邮件

[英]How to forward email using Python

首先,让我说,我已经知道在使用 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)崩溃了,文件也不见了。

对于那些想知道为什么我不只是将 google 设置为自动转发所有内容的人,这是因为我想要一个最终会移动大量邮件的脚本,一次。

谢谢大家!

很有可能,原始电子邮件的 Received: 标题导致 gmail 丢弃该邮件。 在转发之前尝试删除所有这些。

如果这不能解决问题,请打印出标题并对其进行编码以删除所有通常不会出现在新编写的消息中的标题。

然而,为什么要这样前进呢? 从一个 IMAP 帐户中提取并将其直接推送到另一个 IMAP 帐户会更容易。

事实上,您可以使用 Mozilla Thunderbird 添加两个帐户,然后将消息从一个拖放到另一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM