• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Mail Attachement ?

 
Remo Burkhard
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question:
What is the easiest way to attach mails with the javax.mail API?
I did not find a class,nor method. MimeMessage-class. etc did not work.
Thank you.
Remo
 
Stu Glassman
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The ability to add attachments iscontained within MimeMessage, however it's well hidden and far from obvious.
First, you must create a MimeMultipart object (javax.mail.internet). It has a method named addBodyPart(), which we will use to create the body of the method and to add attachments. To this method we will pass an object of type MimeBodyPart (javax.mail.internet).
To create the body of the message, simply use the setText() method of MimeBodyPart.
For each attachment, you'll need a new MimeBodyPart object. To attach the file, you must use the setDataHandler() method. It takes as a parameter a DataHandler object (javax.activation). The DataHandler constructor can take in a FileDataSource object (javax.activation). The FileDataSource constructor can take a File object.
Here's a code snippet. It assumes that
File attachment;
String messageText;
exist and are valid. It also ignore exceptions and error handling:

For alternative methods, see the J2EE API.
Hope this works,
-Stu
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!