使用 JAVA Mail API 发送带附件的电子邮件,无需存储在本地机器中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1502635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send an E-Mail with attachment using JAVA Mail API without storing in local machine
提问by
I have report in my jsppage and I am writing that report in PDF Format.
And I want to send the PDF as E-Mail with attachment, but I don't want store the file in local machine or server, but i want to send an email with the attachment.
我的jsp页面中有报告,我正在以 PDF 格式编写该报告。我想将 PDF 作为带附件的电子邮件发送,但我不想将文件存储在本地机器或服务器中,但我想发送带有附件的电子邮件。
回答by skaffman
If you use Spring's JavaMail API, you can do this sort of thing fairly easily (or at least, as easily as the JavaMail API allows, which isn't much). So you could write something like this:
如果您使用Spring 的 JavaMail API,您可以相当轻松地完成这类事情(或者至少,像 JavaMail API 允许的那样轻松,这并不多)。所以你可以这样写:
JavaMailSenderImpl mailSender = ... instantiate and configure JavaMailSenderImpl here
final byte[] data = .... this holds my PDF data
mailSender.send(new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
// set from, to, subject using helper
helper.addAttachment("my.pdf", new ByteArrayResource(data));
}
});
The attachment data can be any of Spring's Resource abstractions, ByteArrayResourceis just one of them.
附件数据可以是任何 Spring 的 Resource 抽象,ByteArrayResource只是其中之一。
Note that this part of the Spring API stands on its own, it does not require (but does benefit from) the Spring container.
请注意,这部分 Spring API 独立存在,它不需要(但确实受益于)Spring 容器。
回答by dariusz.czyrnek
Since JavaMail 1.4 - mail.jar - contains javax.mail.util.ByteArrayDataSource
由于 JavaMail 1.4 - mail.jar - 包含 javax.mail.util.ByteArrayDataSource
- https://javamail.java.net/nonav/docs/api/javax/mail/util/ByteArrayDataSource.html
- ( https://javamail.java.net/nonav/docs/api/)
- http://www.oracle.com/technetwork/java/javamail/index-138643.html- download location
- https://javamail.java.net/nonav/docs/api/javax/mail/util/ByteArrayDataSource.html
- ( https://javamail.java.net/nonav/docs/api/)
- http://www.oracle.com/technetwork/java/javamail/index-138643.html- 下载位置
regards
问候
回答by jarnbjo
You have to write your own implementation of javax.activation.DataSourceto read the attachment data from an memory instead of using one of the included implementations (to read from a file, a URL, etc.). If you have the PDF report in a byte array, you can implement a DataSource which returns the byte array wrapped in a ByteArrayOutputStream.
您必须编写自己的实现javax.activation.DataSource来从内存中读取附件数据,而不是使用包含的实现之一(从文件、URL 等中读取)。如果您有一个字节数组的 PDF 报告,您可以实现一个 DataSource,它返回包装在 ByteArrayOutputStream 中的字节数组。

