.zip file gets converted to .bin file while sending the email in java

梦想的初衷 提交于 2019-12-11 12:56:37

问题


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>");


来源:https://stackoverflow.com/questions/11554847/zip-file-gets-converted-to-bin-file-while-sending-the-email-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!