您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用python smtplib转发电子邮件

使用python smtplib转发电子邮件

我认为您出错的部分是如何替换邮件中的标头,而且您无需复制邮件,因此,您可以从获取的原始数据中创建邮件后直接对其进行操作从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('IN@R_375_2419@')
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()

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

python 2022/1/1 18:43:02 有415人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶