How can I append a draft email answering an email into a mailbox – imaplib


I want to append an answer to an email as a draft in a Mailbox but the problem is that I need a message object to pass it to the function append of imaplib. The problem is that when I am generating the answer as described here (, I am generating a MimeMultipart so it is not working with append

This is the code I have so far. Any suggestions?

def answer_email(original, answer_body):
    for part in original.walk():
        if (part.get('Content-Disposition')
                and part.get('Content-Disposition').startswith("attachment")):
            part.set_payload("Attachment removed: %s (%s, %d bytes)"
                             % (part.get_filename(),
            del part["Content-Disposition"]
            del part["Content-Transfer-Encoding"]

    new = MIMEMultipart("mixed")
    body = MIMEMultipart("alternative")
    body.attach(MIMEText(answer_body, "plain"))
    body.attach(MIMEText("<html>"+answer_body+"</html>", "html"))

    new["Message-ID"] = email.utils.make_msgid()
    new["In-Reply-To"] = original["Message-ID"]
    new["References"] = original["Message-ID"]
    new["Subject"] = "Re: " + original["Subject"]
    new["To"] = original["Reply-To"] or original["From"]
    new["From"] = "[email protected]"
    return new

imap.append(str(bandeja + '/Gestionados' ), '', imaplib.Time2Internaldate(time()), answer_email(msg, respuesta.choices[0].text).as_string())

Asked By: hugojm



I finally solved the issue by using as_bytes() instead of as_string().

Answered By: hugojm
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.