9

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 !

Péter Török
  • 114,404
  • 31
  • 268
  • 329
moa
  • 121
  • 1
  • 2
  • 6

1 Answers1

16

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));
bluish
  • 26,356
  • 27
  • 122
  • 180
Nikolaus Gradwohl
  • 19,708
  • 3
  • 45
  • 61
  • that's great :) TY very much i just need one more detail: my attach name is untitled-[2]. How to I customizes it? – moa Aug 24 '10 at 12:31
  • 2
    (For posterity, @Nikolaus meant `setFileName` and `MimeBodyPart`, not `getFileName` and `MimeMultipart`.) – dkarp Jan 11 '11 at 16:11