views:

39

answers:

1

Hello,

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 !

+4  A: 

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

MimeBodyPart mbp = new MimeBodyPart();
String data = "any ASCII data";
DataSource ds = new ByteArrayDataSource(data, "application/x-any");
mbp.setDataHandler(new DataHandler(ds));
Nikolaus Gradwohl
that's great :) TY very much i just need one more detail:my attach name is untitled-[2].How to I customizes it?
moa
by using the getFileName method of the MimeMultipart class - see the javadoc of the mail-api at http://java.sun.com/products/javamail/javadocs/javax/mail/internet/MimeBodyPart.html
Nikolaus Gradwohl
yes! that works just fine, ty again :)
moa