首先,让我说,我已经知道这是在 Forwarding an email with 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: header 导致 gmail 丢弃邮件。在转发之前尝试删除所有这些。
如果这不能解决问题,请打印出标题并对其进行编码以删除所有通常不会出现在新撰写的消息中的标题。
但是,为什么要这样转发呢?直接从一个 IMAP 帐户中提取数据并将其推送到另一个 IMAP 帐户会更容易。
事实上,您可以使用 Mozilla Thunderbird 添加两个帐户,只需将消息从一个帐户拖放到另一个帐户即可。
