File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Other JSE/JEE APIs and the fly likes attachment with message.... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Other JSE/JEE APIs
Bookmark "attachment with message...." Watch "attachment with message...." New topic
Author

attachment with message....

ankush dixit
Greenhorn

Joined: Mar 14, 2006
Posts: 4
hi...

i am having problem with sending mails with attachment and message....

i'm able to send mail with message and no attachment and also with attachment and no message...but not both at the same time...

here's the code...

import java.util.Properties;

import javax.mail.Session;
import javax.mail.Message;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;


public class EmailNotification {

public EmailNotification() {

}

public static void sendMail(String to,String from, String subject, String message, String attachmentFileName){
Properties props = new Properties();

String host = "<host name>";

props.put("mail.smtp.host",host);

Session session = Session.getDefaultInstance(props, null);

Message msg = new MimeMessage(session);

try {
msg.setFrom(new InternetAddress(from));

InternetAddress[] address =null ;
address=InternetAddress.parse(to);
msg.setRecipients(Message.RecipientType.TO, address);

BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();

msg.setSubject(subject);


DataSource source = new FileDataSource(attachmentFileName);
messageBodyPart.setDataHandler(new DataHandler(source));
String fileApper = attachmentFileName.substring(attachmentFileName.lastIndexOf("\\")+1);
messageBodyPart.setFileName(fileApper);
messageBodyPart.setText(message);
multipart.addBodyPart(messageBodyPart);

msg.setContent(multipart);


Transport.send(msg);
}
catch(AddressException ae){

}
catch(MessagingException me) {

}

}
}
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18651
    
    8

If you downloaded JavaMail then you have a "demo" directory that contains example code. You will find an example of what you want to do in that directory, I think. You need separate parts for your body text and each of your attachments.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: attachment with message....