dalore
dalore

Reputation:

How do I send a binary attachment in an email with Java using the JavaMail API?

Using JDK1.5 how does one send a binary attachemnt (such as a PDF file) easily using the JavaMail API?

Upvotes: 0

Views: 4701

Answers (3)

cynicalman
cynicalman

Reputation: 5881

Assuming that you don't want to read some links and don't want any external dependencies, you need to use MimeMultipart and BodyPart:

MimeMultipart messageContent = new MimeMultipart();

BodyPart bodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(yourFile);
bodyPart.setDataHandler(new DataHandler(source));
bodyPart.setFileName("MyFile.ext");
bodyPart.setDisposition(Part.ATTACHMENT);

// Then add to your message:
messageContent.addBodyPart(bodyPart);

Attaching a body to the messages is just attaching a BodyPart with disposition Part.INLINE

Upvotes: 4

Cadet Pirx
Cadet Pirx

Reputation:

Have you looked at the JavaMail FAQ? It seems to have little snippets to demonstrate the process (and how to fix a common problem -- running out of memory).

Upvotes: 5

user7094
user7094

Reputation:

If you want to do it easily I'd suggest using Commons-Email! It's built on the JavaMail API, but it makes it much simpler.

There is a sample in the User Guide on how to send email with attachments... it's much easier than using the standard JavaMail API!

Upvotes: 2

Related Questions