python - Python - 回复电子邮件
问题描述
我想使用 python 和 smtp 回复特定消息。我已经看过这些帖子:
如何使用 Python imaplib 回复电子邮件并包含原始消息?
但不幸的是,它只发送带有“---------转发消息----------”的回复,而不是以正常方式回复。
请帮忙!
附上代码
def reply_to_msg(self, original_msg, reply_body):
# fetch msg
self.login_imap(host="imap.gmail.com", port=993, username='username@gmail.com', password="pass",
use_ssl=True)
# Filter by subject because it is unique subject (uuid)
# Get message ID
mail_ids = self.receive_mail_ids(subject_filter=original_msg["Subject"])
msg = MIMEMultipart("mixed")
body = MIMEMultipart("alternative")
text, _ = self.append_orig_text(reply_body, "", original_msg, True)
body.attach(MIMEText(text, 'plain'))
msg.attach(body)
msg.attach(MIMEMessage(original_msg))
msg["Message-ID"] = email.utils.make_msgid()
msg['To'] = original_msg["From"]
msg['Subject'] = "Re: " + original_msg["Subject"]
msg['In-Reply-To'] = msg['References'] = mail_ids[-1]
# send
try:
s = self.login_smtp(host="smtp.gmail.com", port=465, username='username@gmail.com', password="pass", use_ssl=True, use_auth=True)
self.smtp.sendmail(original_msg['To'], [original_msg["From"]], msg.as_string())
except Exception as error:
raise EmailManagerError("sendmail: {}".format(error))
@staticmethod
def append_orig_text(text, html, orig, google=False):
"""
Append each part of the orig message into 2 new variables
(html and text) and return them. Also, remove any
attachments. If google=True then the reply will be prefixed
with ">". The last is not tested with html messages...
"""
newhtml = ""
newtext = ""
for part in orig.walk():
if (part.get('Content-Disposition')
and part.get('Content-Disposition').startswith("attachment")):
part.set_type("text/plain")
part.set_payload("Attachment removed: %s (%s, %d bytes)"
% (part.get_filename(),
part.get_content_type(),
len(part.get_payload(decode=True))))
del part["Content-Disposition"]
del part["Content-Transfer-Encoding"]
if part.get_content_type().startswith("text/plain"):
newtext += "\n"
newtext += part.get_payload(decode=False)
if google:
newtext = newtext.replace("\n", "\n> ")
elif part.get_content_type().startswith("text/html"):
newhtml += "\n"
newhtml += part.get_payload(decode=True).decode("utf-8")
if google:
newhtml = newhtml.replace("\n", "\n> ")
if newhtml == "":
newhtml = newtext.replace('\n', '<br/>')
return (text + '\n\n' + newtext, html + '<br/>' + newhtml)
解决方案
推荐阅读
- bash - 如何将带引号的参数存储在 bash 的变量中?
- java - 为什么 Maven 项目中缺少 SLF4J Logger 和 LoggerFactory 导入?
- asp.net-core - 如何将 ASPNET 网站自动发布到 Linux VPS?
- javascript - 设置状态后如何避免高估项目?
- java - RxJava Flowable 缓存到单个死锁
- python - 用于计算条件发生的数据框
- ruby-on-rails - 为什么在构建我的 docker 存储库时“捆绑安装”返回错误?
- css - 如何在 SquareSpace 博客中显示代码块以获取教程
- git - 使用 Git 时忽略行添加
- python - 不了解此“索引超出范围”错误的原因