Problem with javamail: how to attach a file without creating a file

I am using the javamail API to create an email and attach a file to it.

Is there any way to send email using javamail api without physically creating the file in the file system.

I just want to select some data from the application and attach it as a file in my email

How do I add:

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!

+4
source share
1 answer

If you use 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)); 
+10
source

All Articles