12

我正在尝试编写一个脚本,该脚本会自动将符合特定条件的某些电子邮件转发到另一封电子邮件。

我已经使用 imaplib 和电子邮件工作下载和解析消息,但我不知道如何将整个电子邮件转发到另一个地址。我是否需要从头开始构建新消息,还是可以以某种方式修改旧消息并重新发送?

这是我到目前为止所拥有的(客户端是 imaplib.IMAP4 连接,id 是消息 ID):

import smtplib, imaplib

smtp = smtplib.SMTP(host, smtp_port)
smtp.login(user, passw)

client = imaplib.IMAP4(host)
client.login(user, passw)
client.select('INBOX')

status, data = client.fetch(id, '(RFC822)')
email_body = data[0][1]
mail = email.message_from_string(email_body)

# ...Process message...

# This doesn't work
forward = email.message.Message()
forward.set_payload(mail.get_payload())
forward['From'] = 'source.email.address@domain.com'
forward['To'] = 'my.email.address@gmail.com'

smtp.sendmail(user, ['my.email.address@gmail.com'], forward.as_string())

我确信关于消息的 MIME 内容,我需要做一些稍微复杂的事情。当然有一些简单的方法可以转发整个消息吗?

# This doesn't work either, it just freezes...?
mail['From'] = 'source.email.address@domain.com'
mail['To'] = 'my.email.address@gmail.com'
smtp.sendmail(user, ['my.email.address@gmail.com'], mail.as_string())
4

2 回答 2

23

我认为你错的部分是如何替换消息中的标题,事实上你不需要复制消息,你可以在从你获取的原始数据创建它之后直接操作它从 IMAP 服务器。

您确实省略了一些细节,所以这是我的完整解决方案,其中详细说明了所有细节。请注意,我将 SMTP 连接置于 STARTTLS 模式,因为我需要它,并注意我已将 IMAP 阶段和 SMTP 阶段彼此分开。也许您认为更改消息会以某种方式更改 IMAP 服务器上的消息?如果你这样做了,这应该清楚地告诉你这不会发生。

import smtplib, imaplib, email

imap_host = "mail.example.com"
smtp_host = "mail.example.com"
smtp_port = 587
user = "xyz"
passwd = "xyz"
msgid = 7
from_addr = "from.me@example.com"
to_addr = "to.you@example.com"

# open IMAP connection and fetch message with id msgid
# store message data in email_data
client = imaplib.IMAP4(imap_host)
client.login(user, passwd)
client.select('INBOX')
status, 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)

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

希望这会有所帮助,即使这个答案来得很晚。

于 2010-12-30T21:04:37.090 回答
1

在一个应用程序中,我通过 POP3(使用 poplib)下载消息并使用您的第二种方法转发它们......也就是说,我改变原始消息的 To/From 并发送它,它可以工作。
您是否尝试过在 smtp.sendmail 中查看它停止的位置?

于 2010-12-20T13:55:49.723 回答