如何使用包含大附件(~25 MB)的Java Mail API发送电子邮件?附件是与我们的云存储提供商(Google云端存储)在线存储的文件。该服务的API为每个文件返回InputStream
对象或ReadableByteChannel
对象。
我不能使用ByteArrayDataSource
创建一个MimeBodyPart
,因为它创建了一个驻留在内存中的整个文件的副本,我们得到一个OutOfMemoryError
。
如果是物理文件,我们可以创建一个FileDataSource
对象并附加到电子邮件中。但是我们可以用InputStream
对象来做吗?
我不能增加堆大小,因为它增加到25MB似乎是一个非常糟糕的主意。如果您有任何其他想法,请告诉我。我们正在开发Google App Engine平台。
尝试使用javax.activation.URLDataSource或javax.activation.FileDataSource。否则,您可以创建自己的DataSource适配器类以直接返回给定的InputStream。
public class InputStreamDataSource implements javax.activation.DataSource {
private final InputStream in;
public InputStreamDataSource(final InputStream in) {
if (in == null) {
throw new NullPointerException();
}
this.in = in;
}
@Override
public InputStream getInputStream() throws IOException {
return in;
}
@Override
public OutputStream getOutputStream() throws IOException {
throw new IOException();
}
@Override
public String getContentType() {
return "application/octet-stream";
}
@Override
public String getName() {
return "some name";
}
}
这可能是将InputStream复制到物理文件并使用FileDataSource对象附加它的时候。但最好还是不要作为附件发送,只需将链接发送到云存储中的对象即可。如果您需要控制对云存储中项目的访问权限,请发送signed url。