使用python smtplib转发电子邮件

rob*_*les 11 python email imap smtp smtplib

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

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

这是我到目前为止(client是一个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())
Run Code Online (Sandbox Code Playgroud)

我确定我需要对消息的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())
Run Code Online (Sandbox Code Playgroud)

Fab*_*olm 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()
Run Code Online (Sandbox Code Playgroud)

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