Sending PDF attachment using HTML + plain_text email in Python

I am trying to send a PDF attachment with an email body that summarizes the contents of a PDF file. The body of the email is in both HTML and plain text.

I use the following code to create an email message:

#Part A
logging.debug("   Building standard email with HTML and Plain Text")
msg = MIMEMultipart("alternative")
msg.attach(MIMEText(email_obj.attachments["plain_text"], "plain", _charset="utf-8"))
msg.attach(MIMEText(email_obj.attachments["html_text"], "html", _charset="utf-8"))

#Part B
logging.debug("   Adding PDF report")
pdf_part = MIMEApplication(base64.decodestring(email_obj.attachments["pdf_report"]), "pdf")
pdf_part.add_header('Content-Disposition', 'attachment', filename="pdf_report.pdf")
logging.debug("   Attaching PDF report")
msg.attach(pdf_part)

My problem is that my mailbox disappears if I attach the PDF. If I comment on the code that attaches the PDF (Part B), the body of the email will appear.

If I'm wrong, it looks like my PDF attachment is overwriting the body of the email.

+4
source share
1 answer

. MIME "multipart/mixed". MIME- "multipart/alternative" , HTML. - PDF

pdfAttachment = MIMEApplication(pdf, _subtype = "pdf")
pdfAttachment.add_header('content-disposition', 'attachment', filename = ('utf-8', '', 'payment.pdf'))
text = MIMEMultipart('alternative')
text.attach(MIMEText("Some plain text", "plain", _charset="utf-8"))
text.attach(MIMEText("<html><head>Some HTML text</head><body><h1>Some HTML Text</h1> Another line of text</body></html>", "html", _charset="utf-8"))
message = MIMEMultipart('mixed')
message.attach(text)
message.attach(pdfAttachment)
message['Subject'] = 'Test multipart message'
f = open("message.msg", "wb")
f.write(bytes(message.as_string(), 'utf-8'))
f.close()

" " ( ) (Ctrl-U Thunderbird)

+9

Source: https://habr.com/ru/post/1534466/


All Articles