Estoy tratando de responder a un correo electrónico utilizando Python 3.4. El destinatario del correo electrónico utilizará Outlook (desafortunadamente) y es importante que Outlook reconozca la respuesta y muestre el hilo correctamente.
El código que tengo actualmente es:
def send_mail_multi(headers, text, msgHtml="", orig=None): """ """ msg = MIMEMultipart('mixed') # Create message container - the correct MIME type is multipart/alternative. body = MIMEMultipart('alternative') for k,v in headers.items(): if isinstance(v, list): v = ', '.join(v) msg.add_header(k, v) # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. body.attach(MIMEText(text, 'plain')) if msgHtml != "": body.attach(MIMEText(msgHtml, 'html')) msg.attach(body) if orig is not None: msg.attach(MIMEMessage(get_reply_message(orig))) # Fix subject msg["Subject"] = "RE: "+orig["Subject"].replace("Re: ", "").replace("RE: ", "") msg['In-Reply-To'] = orig["Message-ID"] msg['References'] = orig["Message-ID"]+orig["References"].strip() msg['Thread-Topic'] = orig["Thread-Topic"] msg['Thread-Index'] = orig["Thread-Index"] send_it(msg['From'], msg['To'], msg)
get_reply_message
está eliminando cualquier archivo adjunto como en esta respuesta . send_it
función send_it
establece el encabezado de ID de mensaje y utiliza la configuración SMTP adecuada. Luego llama smtplib.sendmail(fr, to, msg.as_string())
msg.attach(MIMEMessage(...))
¿Alguna idea sobre cómo hacer esto? ¿Me he perdido algún encabezado?
Aclamaciones,
Andreas
Me tomó un tiempo pero lo siguiente parece funcionar:
def send_mail_multi(headers, text, msgHtml="", orig=None): """ """ msg = MIMEMultipart('mixed') # Create message container - the correct MIME type is multipart/alternative. body = MIMEMultipart('alternative') for k,v in headers.items(): if isinstance(v, list): v = ', '.join(v) msg.add_header(k, v) # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. if orig is not None: text, msgHtml2 = append_orig_text(text, msgHtml, orig, False) # Fix subject msg["Subject"] = "RE: "+orig["Subject"].replace("Re: ", "").replace("RE: ", "") msg['In-Reply-To'] = orig["Message-ID"] msg['References'] = orig["Message-ID"]#+orig["References"].strip() msg['Thread-Topic'] = orig["Thread-Topic"] msg['Thread-Index'] = orig["Thread-Index"] body.attach(MIMEText(text, 'plain')) if msgHtml != "": body.attach(MIMEText(msgHtml2, 'html')) msg.attach(body) send_it(msg) 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', '
') return (text+'\n\n'+newtext, html+'
'+newhtml)
El código necesita un poco de información, pero al igual que Outlook lo muestra correctamente (con las opciones Siguiente / Anterior). No había necesidad de crear encabezados de From, Send, To, Subject
mano, agregando el contenido trabajado.
Espero que esto ahorre el tiempo de alguien más