【问题标题】:Forwarding Mail Using Python With added new contents使用 Python 转发邮件并添加新内容
【发布时间】:2016-02-29 13:02:18
【问题描述】:

替换像 from,to,sub 这样的标题后,我可以将邮件转发到另一个电子邮件地址。 但是如何通过添加更多附件和更多文本或 html 内容来转发邮件。

正如我们在 gmail 中看到的,新内容应该显示在转发的消息内容之前。关于我们如何实现这一点的任何想法?

转发的邮件可以是多部分的,也可以不是。

但由于我们添加了新内容,它将是多部分的

我试过下面的代码

# open IMAP connection and fetch message with id msgid
# store message data in email_data
client = imaplib.IMAP4_SSL(imap_host,993)
client.login(user, passwd)
client.select('INBOX')
result, data = client.uid('fetch', msg_id, "(RFC822)")
client.close()
client.logout()

# create a Message instance from the email data
message = email.message_from_string(data[0][1])

# replace headers (could do other processing here)
message.replace_header("From", from_addr)
message.replace_header("To", to_addr)
message.replace_header("Subject", "Fwd:"+ message["Subject"].replace("FWD: ", "").replace("Fwd: ","" ))


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

【问题讨论】:

  • 嗨,你找到解决方案了吗?
  • @Ankur Sharma,还没有
  • 关于此的任何消息。我也在摆弄这个。

标签: python email smtplib imaplib


【解决方案1】:

我能够使用email 包来实现这一点,并将原始电子邮件作为一部分附加:

from email.message import Message
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.message import MIMEMessage
from email import message_from_bytes

raw_email = get_raw_email() # get the original email from wherever
original_email = message_from_bytes(raw_email)

part1 = MIMEText("This is new content")
part2 = MIMEMessage(original_email)

new_email = MIMEMultipart()
new_email['Subject'] = "My subject"
new_email['From'] = 'abc@xyz.com'
new_email['To'] = '123@456.com'
new_email.attach(part1)
new_email.attach(part2)

【讨论】:

    猜你喜欢
    • 2016-09-23
    • 2020-02-02
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2012-11-15
    相关资源
    最近更新 更多