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

Question:

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 (https://stackoverflow.com/questions/2182196/how-do-i-reply-to-an-email-using-the-python-imaplib-and-include-the-original-mes), 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_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"]

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

    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

||

Answers:

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.