下面列出了怎么用org.springframework.core.io.InputStreamSource的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Create an Activation Framework DataSource for the given InputStreamSource.
* @param inputStreamSource the InputStreamSource (typically a Spring Resource)
* @param contentType the content type
* @param name the name of the DataSource
* @return the Activation Framework DataSource
*/
protected DataSource createDataSource(
final InputStreamSource inputStreamSource, final String contentType, final String name) {
return new DataSource() {
@Override
public InputStream getInputStream() throws IOException {
return inputStreamSource.getInputStream();
}
@Override
public OutputStream getOutputStream() {
throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
}
@Override
public String getContentType() {
return contentType;
}
@Override
public String getName() {
return name;
}
};
}
protected Mono<InputStreamSource> convertResource(String resource) {
if (resource.startsWith("http")) {
return WebClient.create()
.get()
.uri(resource)
.accept(MediaType.APPLICATION_OCTET_STREAM)
.exchange()
.flatMap(rep -> rep.bodyToMono(Resource.class));
} else {
try {
return Mono.just(new InputStreamResource(new FileInputStream(resource)));
} catch (FileNotFoundException e) {
return Mono.error(e);
}
}
}
@Override
public boolean sendEmail(String from, String to, String cc, String title, String content, String attachmentFilename, InputStreamSource inputStreamSource) {
MimeMessage message = null;
try {
message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
if(StringUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
helper.setSubject(title);
helper.setText(content, true);
if(inputStreamSource!=null) {
helper.addAttachment(attachmentFilename, inputStreamSource);
}
javaMailSender.send(message);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private void sendEmailMessage(String tplCode, String from, String to, String cc, String title,
String content,MessageTemplate messageTemplate,
String attachmentFilename, InputStreamSource inputStreamSource){
try {
EmailSender emailSender = getEmailSender(messageTemplate);
boolean isSuccess = false;
if(inputStreamSource!=null){
isSuccess = emailSender.sendEmail(from, to, cc, title, content,attachmentFilename,inputStreamSource);
}else {
isSuccess = emailSender.sendEmail(from, to, cc, title, content);
}
saveMessage(1, tplCode, to, content, isSuccess);
}catch (Exception e){
logger.error(e.getMessage(), e);
saveMessage(1, tplCode, to, content, false);
}
}
@Override
public boolean sendEmail(String from, String to, String cc, String title, String content, String attachmentFilename, InputStreamSource inputStreamSource) {
MimeMessage message = null;
try {
message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
if(StringUtils.isNotEmpty(cc)) {
helper.setCc(cc);
}
helper.setSubject(title);
helper.setText(content, true);
if(inputStreamSource!=null) {
helper.addAttachment(attachmentFilename, inputStreamSource);
}
javaMailSender.send(message);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private void sendEmailMessage(String tplCode, String from, String to, String cc, String title,
String content,MessageTemplate messageTemplate,
String attachmentFilename, InputStreamSource inputStreamSource){
try {
EmailSender emailSender = getEmailSender(messageTemplate);
boolean isSuccess = false;
if(inputStreamSource!=null){
isSuccess = emailSender.sendEmail(from, to, cc, title, content,attachmentFilename,inputStreamSource);
}else {
isSuccess = emailSender.sendEmail(from, to, cc, title, content);
}
saveMessage(1, tplCode, to, content, isSuccess);
}catch (Exception e){
logger.error(e.getMessage(), e);
saveMessage(1, tplCode, to, content, false);
}
}
/**
* Create an Activation Framework DataSource for the given InputStreamSource.
* @param inputStreamSource the InputStreamSource (typically a Spring Resource)
* @param contentType the content type
* @param name the name of the DataSource
* @return the Activation Framework DataSource
*/
protected DataSource createDataSource(
final InputStreamSource inputStreamSource, final String contentType, final String name) {
return new DataSource() {
@Override
public InputStream getInputStream() throws IOException {
return inputStreamSource.getInputStream();
}
@Override
public OutputStream getOutputStream() {
throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
}
@Override
public String getContentType() {
return contentType;
}
@Override
public String getName() {
return name;
}
};
}
/**
* Create an Activation Framework DataSource for the given InputStreamSource.
* @param inputStreamSource the InputStreamSource (typically a Spring Resource)
* @param contentType the content type
* @param name the name of the DataSource
* @return the Activation Framework DataSource
*/
protected DataSource createDataSource(
final InputStreamSource inputStreamSource, final String contentType, final String name) {
return new DataSource() {
@Override
public InputStream getInputStream() throws IOException {
return inputStreamSource.getInputStream();
}
@Override
public OutputStream getOutputStream() {
throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
}
@Override
public String getContentType() {
return contentType;
}
@Override
public String getName() {
return name;
}
};
}
/**
* Create an Activation Framework DataSource for the given InputStreamSource.
* @param inputStreamSource the InputStreamSource (typically a Spring Resource)
* @param contentType the content type
* @param name the name of the DataSource
* @return the Activation Framework DataSource
*/
protected DataSource createDataSource(
final InputStreamSource inputStreamSource, final String contentType, final String name) {
return new DataSource() {
@Override
public InputStream getInputStream() throws IOException {
return inputStreamSource.getInputStream();
}
@Override
public OutputStream getOutputStream() {
throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
}
@Override
public String getContentType() {
return contentType;
}
@Override
public String getName() {
return name;
}
};
}
public void sendTplEmail(String tplCode, String from, String to, String cc, String title,
String attachmentFilename, InputStreamSource inputStreamSource,
Map<String, Object> dataMap) {
MessageTemplate messageTemplate = messagetemplateRepository.findByCode(tplCode);
String content = getContent(messageTemplate.getContent(), dataMap);
sendEmailMessage(tplCode,from,to,cc,title,content,messageTemplate,attachmentFilename,inputStreamSource);
}
@GetMapping(value = "/download/{fileName}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public InputStreamSource downloadTemplate(final HttpServletRequest request, final HttpServletResponse response,
@PathVariable String fileName) {
if ("Template".equalsIgnoreCase(fileName)) {
response.setHeader("Content-Disposition", "attachment;filename=node-upload-template.xlsx");
return new InputStreamResource(this.getFileInputStream("static/doc/node-upload-template.xlsx"));
} else if ("help-doc".equalsIgnoreCase(fileName)) {
response.setHeader("Content-Disposition", "attachment;filename=cymbal-manual.docx");
return new InputStreamResource(this.getFileInputStream("static/doc/cymbal-manual.docx"));
}
return null;
}
public void sendTplEmail(String tplCode, String from, String to, String cc, String title,
String attachmentFilename, InputStreamSource inputStreamSource,
Map<String, Object> dataMap) {
MessageTemplate messageTemplate = messagetemplateRepository.findByCode(tplCode);
String content = getContent(messageTemplate.getContent(), dataMap);
sendEmailMessage(tplCode,from,to,cc,title,content,messageTemplate,attachmentFilename,inputStreamSource);
}
/**
* 发送HTML格式,带有附件的邮件
* @param to
* @param subject
* @param body
* @param attachmentName
* @param iss
* @throws MessagingException
*/
public void sendHtmlEmailWithAttachment(String to, String subject, String body, String attachmentName, InputStreamSource iss) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(sender);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(body, true);
// 可以增加多个附件,每个附件调用addAttachement
helper.addAttachment(attachmentName, iss);
mailSender.send(mimeMessage);
}
/**
* 暂时只支持这几种类型
*
* @param paramType
* @return the result
*/
public static boolean isMutlipart(Class paramType) {
return (byte[].class == paramType ||
InputStream.class.isAssignableFrom(paramType) ||
Reader.class.isAssignableFrom(paramType) ||
File.class.isAssignableFrom(paramType) ||
InputStreamSource.class.isAssignableFrom(paramType));
}
/**
* 发送带附件的邮件
* @param to 收件人列表
* @param subject 邮件标题
* @param content 邮件内容
* @param inputStreamSource 附件streamSource,可以这样获得:new ByteArrayResource(ByteArrayOutputStream.toByteArray());
* @param fileName 附件的文件名
*/
public void sendAttachmentsMail(String to, String subject, String content, InputStreamSource inputStreamSource, String fileName){
MimeMessage message = sender.createMimeMessage();
try {
MimeMessageHelper helper = setInfoByHelper(to, subject, content, message);
helper.addAttachment(fileName, inputStreamSource);
sender.send(message);
logger.debug("带附件的邮件已经发送。");
} catch (MessagingException e) {
logger.error("发送带附件的邮件时发生异常!", e);
}
}
@Test
public void testSmbToByteArrayInputStream() throws Exception{
TimeCounter t = new TimeCounter("testSmbToByteArrayInputStream");
t.start();
String path = "smb://administrator:[email protected]/install/ftp/新建文本文档.txt";
InputStreamSource ins = new SmbToByteArrayInputStreamSource(path);
List<String> list = FileUtils.readAsList(ins.getInputStream());
for(String str : list){
System.out.println(str);
}
t.stop();
}
@Test
public void testCopyToLocal() throws Exception{
TimeCounter t = new TimeCounter("testCopyToLocal");
t.start();
String path = "smb://administrator:[email protected]/install/ftp/email-attachements/批量受理模板2-20140911102904-023442.xlsx";
InputStreamSource ins = new SmbToByteArrayInputStreamSource(path);
FileUtils.writeInputStreamTo(ins.getInputStream(), "D:/email-attachements", "smbexcel.xls");
}
private XmlSuite loadSuite(String suitePath, InputStreamSource resource) throws IOException {
IFileParser<XmlSuite> parser = getParser(suitePath);
try (InputStream inputStream = resource.getInputStream()) {
XmlSuite xmlSuite = parser.parse(suitePath, inputStream, true);
xmlSuite.setParallel(XmlSuite.ParallelMode.getValidParallel(parallel));
xmlSuite.setThreadCount(threadCount);
xmlSuite.setTimeOut(timeOut);
LOG.info("Test are running in: {} type of parallel mode, thread count: {} and with test timeout: {}", parallel.toUpperCase(), threadCount, timeOut);
return xmlSuite;
}
}
@Test
public void sendMailWithExcel() throws IOException {
String[] headers = {"col1","col2","col3"};
// 声明一个工作薄
HSSFWorkbook wb = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(headers[i]);
}
int rowIndex = 1;
for(int j=0; j<3; j++){
row = sheet.createRow(rowIndex);
rowIndex++;
HSSFCell cell1 = row.createCell(0);
cell1.setCellValue(j);
cell1 = row.createCell(1);
cell1.setCellValue(j+1);
cell1 = row.createCell(2);
cell1.setCellValue(j+2);
}
for (int i = 0; i < headers.length; i++) {
sheet.autoSizeColumn(i);
}
ByteArrayOutputStream os = new ByteArrayOutputStream(1000);
wb.write(os);
wb.close();
InputStreamSource iss = new ByteArrayResource(os.toByteArray());
os.close();
mailService.sendAttachmentsMail("[email protected]",
"attachmentMail subject",
"I have an attachment",
iss, "abc1.xlsx");
}
/**
* Creates a ResourceInputSource for the given {@link InputStreamSource}
* @param streamSource The InputStreamSource to be parsed
* @throws IOException Indicates a problem in accessing the underlying stream
*/
public ResourceInputSource(InputStreamSource streamSource) throws IOException {
setByteStream(streamSource.getInputStream());
this.streamSource = streamSource;
}
public Map<String, InputStreamSource> getAttachments() {
return attachments;
}
public void setAttachments(Map<String, InputStreamSource> attachments) {
this.attachments = attachments;
}
public void addAttachment(String name, InputStreamSource attachment) {
attachments.put(name, attachment);
}
public Map<String, InputStreamSource> getInlines() {
return inlines;
}
public void setInlines(Map<String, InputStreamSource> inlines) {
this.inlines = inlines;
}
public void addInline(String name, InputStreamSource inline) {
inlines.put(name, inline);
}
/**
* Add an inline element to the MimeMessage, taking the content from an
* {@code org.springframework.core.InputStreamResource}, and
* specifying the content type explicitly.
* <p>You can determine the content type for any given filename via a Java
* Activation Framework's FileTypeMap, for example the one held by this helper.
* <p>Note that the InputStream returned by the InputStreamSource implementation
* needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
* {@code getInputStream()} multiple times.
* <p><b>NOTE:</b> Invoke {@code addInline} <i>after</i> {@code setText};
* else, mail readers might not be able to resolve inline references correctly.
* @param contentId the content ID to use. Will end up as "Content-ID" header
* in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>".
* Can be referenced in HTML source via src="cid:myId" expressions.
* @param inputStreamSource the resource to take the content from
* @param contentType the content type to use for the element
* @throws MessagingException in case of errors
* @see #setText
* @see #getFileTypeMap
* @see #addInline(String, org.springframework.core.io.Resource)
* @see #addInline(String, javax.activation.DataSource)
*/
public void addInline(String contentId, 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 a fresh stream for every call.");
}
DataSource dataSource = createDataSource(inputStreamSource, contentType, "inline");
addInline(contentId, dataSource);
}
/**
* Add an attachment to the MimeMessage, taking the content from an
* {@code org.springframework.core.io.InputStreamResource}.
* <p>The content type will be determined by the given filename for
* the attachment. Thus, any content source will be fine, including
* temporary files with arbitrary filenames.
* <p>Note that the InputStream returned by the InputStreamSource
* implementation needs to be a <i>fresh one on each call</i>, as
* JavaMail will invoke {@code getInputStream()} multiple times.
* @param attachmentFilename the name of the attachment as it will
* appear in the mail
* @param inputStreamSource the resource to take the content from
* (all of Spring's Resource implementations can be passed in here)
* @throws MessagingException in case of errors
* @see #addAttachment(String, java.io.File)
* @see #addAttachment(String, javax.activation.DataSource)
* @see org.springframework.core.io.Resource
*/
public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)
throws MessagingException {
String contentType = getFileTypeMap().getContentType(attachmentFilename);
addAttachment(attachmentFilename, inputStreamSource, contentType);
}
/**
* Add an attachment to the MimeMessage, taking the content from an
* {@code org.springframework.core.io.InputStreamResource}.
* <p>Note that the InputStream returned by the InputStreamSource
* implementation needs to be a <i>fresh one on each call</i>, as
* JavaMail will invoke {@code getInputStream()} multiple times.
* @param attachmentFilename the name of the attachment as it will
* appear in the mail
* @param inputStreamSource the resource to take the content from
* (all of Spring's Resource implementations can be passed in here)
* @param contentType the content type to use for the element
* @throws MessagingException in case of errors
* @see #addAttachment(String, java.io.File)
* @see #addAttachment(String, javax.activation.DataSource)
* @see org.springframework.core.io.Resource
*/
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 a fresh stream for every call.");
}
DataSource dataSource = createDataSource(inputStreamSource, contentType, attachmentFilename);
addAttachment(attachmentFilename, dataSource);
}
/**
* Add an inline element to the MimeMessage, taking the content from an
* {@code org.springframework.core.InputStreamResource}, and
* specifying the content type explicitly.
* <p>You can determine the content type for any given filename via a Java
* Activation Framework's FileTypeMap, for example the one held by this helper.
* <p>Note that the InputStream returned by the InputStreamSource implementation
* needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
* {@code getInputStream()} multiple times.
* <p><b>NOTE:</b> Invoke {@code addInline} <i>after</i> {@code setText};
* else, mail readers might not be able to resolve inline references correctly.
* @param contentId the content ID to use. Will end up as "Content-ID" header
* in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>".
* Can be referenced in HTML source via src="cid:myId" expressions.
* @param inputStreamSource the resource to take the content from
* @param contentType the content type to use for the element
* @throws MessagingException in case of errors
* @see #setText
* @see #getFileTypeMap
* @see #addInline(String, org.springframework.core.io.Resource)
* @see #addInline(String, javax.activation.DataSource)
*/
public void addInline(String contentId, 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 a fresh stream for every call.");
}
DataSource dataSource = createDataSource(inputStreamSource, contentType, "inline");
addInline(contentId, dataSource);
}