首页 > 解决方案 > Python - 回复电子邮件

问题描述

我想使用 python 和 smtp 回复特定消息。我已经看过这些帖子:

使用 python 3.4 回复电子邮件

如何使用 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)

标签: pythonemailsmtp

解决方案


推荐阅读