javamail problem: how to attach file without creating file

折月煮酒 提交于 2019-12-10 14:22:18

问题


I'm using javamail API to create e-mail and attach a file to it.

Is there a way to send e-mail with attach using javamail api without physically creating file on file system.

I just want to pick some data from app and attach it as file in my e-mail

How should I attach:

try {
            // create a message
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            InternetAddress[] address = {new InternetAddress(to)};
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject(subject);

            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(msgText1);

            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            **mbp2.attachFile(filename);**


            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

            // add the Multipart to the message
            msg.setContent(mp);

            // set the Date: header
            msg.setSentDate(new Date());

            // send the message
            Transport.send(msg);

TY very much all !


回答1:


If you are using JavaMail 1.4 or higher you can use java.mail.util.ByteArrayDataSource like this

MimeBodyPart mbp = new MimeBodyPart();
String data = "any ASCII data";
DataSource ds = new ByteArrayDataSource(data, "application/x-any");
mbp.setDataHandler(new DataHandler(ds));


来源:https://stackoverflow.com/questions/3556091/javamail-problem-how-to-attach-file-without-creating-file

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