0

I'm sending a excel file to some bot through python. The bot is reject the message saying no excel file is found. My code is this:

 msg_id = Header(email.utils.make_msgid('e_shop').encode('utf-8'), 'UTF-8').encode()
 message = MIMEMultipart()
 message["From"] = sender_email
 message["To"] = receiver_email
 message["Subject"] = subject
 message["References"] = msg_id
 html = """\
     <html>
            <body>
                <p>VEH NO.""" + num +""" REPORT </p>
                <br><br><br><br><br>
                <p>THANKING YOU <p>
            </body>
            </html>
        """

part2 = MIMEText(html,"html")

with open(str(pdf_file_path), "rb") as attachment:
            pdf_part = MIMEBase("application", "octet-stream")
            pdf_part.set_payload(attachment.read())
        encoders.encode_base64(pdf_part)

        pdf_part.add_header(
            "Content-Disposition",
            'attachment; filename= {}'.format(file_name+'.pdf'),
        )

        with open(str(excel_file_path), "rb") as attachment:
            excel_part = MIMEBase("application", "octet-stream")
            excel_part.set_payload(attachment.read())
        encoders.encode_base64(excel_part)
        excel_part.add_header(
            "Content-Disposition",
            'attachment; filename= {}'.format(file_name+'.xlsx'),
        )
message.attach(pdf_part)
message.attach(excel_part)
message.attach(part2)

text = message.as_string()
context = ssl.create_default_context()

with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(sender_email, pwd)
    res = server.sendmail(sender_email, receiver_email, text)

In this way it reject my email but during sending email with attachment manually, the bot didn't reject the email. So after checking my sent mail, I notice that in the Content-Disposition of both the type of mail are slight different

1.Content-Disposition of mail sent with python script

   Content-Disposition:  attachment; filename=file_name.pdf

2.Content-Disposition of manual mail sent

   Content-Disposition:  attachment; filename="file_name.pdf"

And also here in this answer they have add the filename in quotes add excel file attachment when sending python email.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Pratik Sharma
  • 165
  • 2
  • 9
  • See [this question about content-type](https://stackoverflow.com/a/4212908/857727). – arnt Aug 31 '20 at 09:13
  • Does it work if you follow the approach used in [this answer](https://stackoverflow.com/a/63538330/5320906)? – snakecharmerb Aug 31 '20 at 09:17
  • Okay will use that. And the second thing is that I want to send mail with some text, html and 2 attachment of pdf and xlsx. Hence what will the mimetype I must use ? @snakecharmerb – Pratik Sharma Aug 31 '20 at 14:49

0 Answers0