您的位置:首页 > 编程语言 > Java开发

JavaMail带附件时出错

2017-12-07 10:14 120 查看


JavaMail requires an InputStreamSource that creates a fresh stream for every

// 添加附件的方法

public void addAttachment(String attachmentFilename, DataSource dataSource) throws MessagingException {
Assert.notNull(attachmentFilename, "Attachment filename must not be null");
Assert.notNull(dataSource, "DataSource must not be null");

try {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDisposition("attachment");
mimeBodyPart.setFileName(MimeUtility.encodeText(attachmentFilename));
mimeBodyPart.setDataHandler(new DataHandler(dataSource));
this.getRootMimeMultipart().addBodyPart(mimeBodyPart);
} catch (UnsupportedEncodingException var4) {
throw new MessagingException("Failed to encode attachment filename", var4);
}
}

public void addAttachment(String attachmentFilename, File file) throws MessagingException {
Assert.notNull(file, "File must not be null");
FileDataSource dataSource = new FileDataSource(file);
dataSource.setFileTypeMap(this.getFileTypeMap());
this.addAttachment(attachmentFilename, (DataSource)dataSource);
}

public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource) throws MessagingException {
String contentType = this.getFileTypeMap().getContentType(attachmentFilename);
this.addAttachment(attachmentFilename, inputStreamSource, contentType);
}

public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource, String contentType) throws MessagingException {
Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
if (inputStreamSource instanceof Resource && ((Resource)inputStreamSource).isOpen()) {
throw new IllegalArgumentException("Passed-in Resource contains an open stream: invalid argument. JavaMail requires an InputStreamSource that creates
4000
a fresh stream for every call.");
} else {
DataSource dataSource = this.createDataSource(inputStreamSource, contentType, attachmentFilename);
this.addAttachment(attachmentFilename, dataSource);
}
}


InputStreamResource inputStreamResource

messageHelper.addAttachment(MimeUtility.encodeWord(fileName), new ByteArrayResource(IOUtils.toByteArray(inputStreamResource.getInputStream())));

流不匹配会导致报错。通过转换成对应的流即可解决
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: