我正在使用 Apache commons 文件上传 API 将文件从 JSP 存储到临时目录中的 servlet,但我不知道下一步应该做什么才能使用 javamail API 将电子邮件作为附件发送。
如何使用 Apache Fileupload API 检索写入临时目录中的文件,并将它们作为附件发送到邮件服务器。将这些文件写入内存或磁盘对我有何帮助?
最佳答案
这是一个例子:
private static void notify(String subject, String text,
File attachment, String from, String to) throws Exception {
Context context = new InitialContext();
Session sess = (Session)context.lookup("java:comp/env/mail/session");
MimeMessage message = new MimeMessage(sess);
message.setSubject(subject, "UTF-8");
if (attachment == null) {
message.setText(text, "UTF-8");
} else {
MimeMultipart mp = null;
MimeBodyPart part1 = new MimeBodyPart();
part1.setText(text, "UTF-8");
MimeBodyPart part2 = new MimeBodyPart();
part2.setDataHandler(new DataHandler(new FileDataSource(attachement)));
part2.setFileName(file.getName());
mp = new MimeMultipart();
mp.addBodyPart(part1);
mp.addBodyPart(part2);
message.setContent(mp);
}
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Transport.send(message);
}
在此示例中,使用了 FileDataSource,这意味着附件必须首先保存为文件。 我有时会使用自制的 MemoryDataSource 来代替。这是代码:
package com.lagalerie.mail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.DataSource;
public class MemoryDataSource implements DataSource {
private String name;
private String contentType;
private byte content[] = {};
public MemoryDataSource(String name, String contentType) {
this.name = name;
this.contentType = contentType;
}
public String getContentType() {
return contentType;
}
public InputStream getInputStream() {
return new ByteArrayInputStream(content);
}
public String getName() {
return name;
}
public OutputStream getOutputStream() {
return new ByteArrayOutputStream() {
@Override
public void close() {
content = toByteArray();
}
};
}
}
关于java - 如何使用 Apache 文件上传启用附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2704103/