【发布时间】:2012-01-22 10:38:35
【问题描述】:
首先,让我说,我已经知道这是在Forwarding an email with python smtplib 提出的问题。
我发布与该问题密切相关的内容的原因是,我尝试使用该问题的答案,尝试更改内容,搜索 Google 并无情地对此进行了大约 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 设置为自动转发所有内容的人,这是因为我想要一个最终会一次性移动大量邮件的脚本。
谢谢大家!
【问题讨论】:
-
在调试器中单步调试您的代码。当您到达
sendmail行时,检查局部变量的值以确保它们是您想要的。如果这不起作用,请添加一条发送虚拟消息的相邻行,看看是否有效。 (FWIW 代码乍一看还不错。) -
感谢您的建议,我做了这两个,虚拟行工作正常并发送一条说“测试”的行
标签: python smtp gmail forward gmail-imap