简体   繁体   中英

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

使用JDK1.5 如何使用JavaMail API 轻松发送二进制附件(如PDF 文件)?

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).

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM