使用python smtplib转发电子邮件

时间:2010-04-26 21:54:34

标签: python email smtp imap smtplib

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

我使用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())

2 个答案:

答案 0 :(得分:18)

我认为您错误的部分是如何替换邮件中的标题,以及您不需要复制邮件的事实,您可以在从原始文件创建邮件后直接对其进行操作您从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()

希望这有助于即使这个答案来得太晚。

答案 1 :(得分:0)

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

相关问题