gpt4 book ai didi

python - 使用 Python 转发邮件并添加新内容

转载 作者:行者123 更新时间:2023-12-03 21:35:58 28 4
gpt4 key购买 nike

替换诸如 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()

最佳答案

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

关于python - 使用 Python 转发邮件并添加新内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35700280/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com