.zip file gets converted to .bin file while sendin

2019-08-10 11:17发布

问题:

I am trying to send mail using below snippet with the zip file as attachment,I am able to send the email but the attachment which is zip file gets converted to some .bin file. Do I need to set some properties? Why zip file gets converted to .bin file?

Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.host", "smtp.gmail.com");

            Session mailSession = Session.getDefaultInstance(props, null);
            mailSession.setDebug(true);
            Transport transport = mailSession.getTransport();

            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject("HTML  mail with images");
            message.setFrom(new InternetAddress("b@gmail.com"));
            message.addRecipient(Message.RecipientType.TO,
                 new InternetAddress("a@gmail.com"));
            MimeMultipart multipart = new MimeMultipart("related");

            // first part  (the html)
            BodyPart messageBodyPart = new MimeBodyPart();
            String htmlText = "PFA Query Output.";
            messageBodyPart.setContent(htmlText, "text/html");

            // add it
            multipart.addBodyPart(messageBodyPart);

            // second part (the image)
            messageBodyPart = new MimeBodyPart();
            DataSource fds = new FileDataSource(zipFilePath);
            messageBodyPart.setDataHandler(new DataHandler(fds));
            messageBodyPart.setHeader("Content-ID","<image>");

            // add it
            multipart.addBodyPart(messageBodyPart);

            // put everything together
            message.setContent(multipart);

            transport.connect();
            transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
            transport.close();

回答1:

Remove messageBodyPart.setHeader("Content-ID","<image>") if you're not sending image.

Add follwing statement set attachment filename,

  messageBodyPart.setFileName(zipFilePath);


回答2:

Instead of

 DataSource fds = new FileDataSource(zipFilePath);

try

 DataSource fds = new FileDataSource(new File(zipFilePath));

Also try removing,

 messageBodyPart.setHeader("Content-ID","<image>");


标签: java email smtp