如何使用InputStream和Spring发送带有附件的电子邮件?

nukf8bse  于 2022-09-18  发布在  Spring
关注(0)|答案(5)|浏览(318)

情况是这样的:

首先,我们在内存中生成一个文件,我们可以得到一个InputStream对象。其次,InputStream对象必须作为电子邮件的附件发送。语言是Java,我们使用Spring来发送电子邮件。

我找到了很多信息,但我找不到如何使用InputStream发送电子邮件附件。我试着这样做:

InputStreamSource iss= new InputStreamResource(new FileInputStream("c:\a.txt"));
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.addAttachment("attachment", iss);

但我得到了一个例外:

传入的资源包含开放流:无效参数。JavaMail需要一个InputStreamSource来为每个调用创建一个新的流。

hrysbysz

hrysbysz1#

对于在内存中生成的文件,您可以使用ByteArrayResource。只需使用Apache Commons IO库中的IOUtils转换InputStream对象。

这很简单:

helper.addAttachment("attachement",
new ByteArrayResource(IOUtils.toByteArray(inputStream)));
snvhrwxg

snvhrwxg2#

使用Java Mail MimeMessageHelper查看Spring参考第24.3章

这个例子就是从那里开始的,我认为它确实想让您这样做:

JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("mail.host.com");

MimeMessage message = sender.createMimeMessage();

// use the true flag to indicate you need a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo("test@host.com");

helper.setText("Check out this image!");

// let's attach the infamous windows Sample file (this time copied to c:/)
FileSystemResource resource = new FileSystemResource(new File("c:/Sample.jpg"));

helper.addAttachment("CoolImage.jpg", resource );

sender.send(message);

如果要使用Stream,则可以使用

ByteArrayResource resource = new ByteArrayResource(IOUtils.toByteArray(inputStream)));

而不是文件系统资源

qnyhuwrf

qnyhuwrf3#

您可以简单地实现InputStreamSource,并根据请求在其中传递新的InputStream:

InputStreamSource iss = new InputStreamSource() {
    @Override
    public InputStream getInputStream() throws IOException {
        // provide fresh InputStream
        return new FileInputStream("c:\a.txt");
    }
}
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.addAttachment("attachment", iss);
x0fgdtte

x0fgdtte4#

//inlineFileObjectCreated--可以为示例创建StringBuilder对象

ByteArrayDataSource source = new ByteArrayDataSource("file name", "contentType", inlineFileObjectCreated.getBytes() );

                JavaMailSender mailSender = (JavaMailSender) ServicesHome.getService("javaMailSender");
                MimeMessage mimeMessage = mailSender.createMimeMessage();
                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
                mimeMessageHelper.setTo(toArray);           
                mimeMessageHelper.setSubject("");
                mimeMessageHelper.setText("");
                mimeMessageHelper.addAttachment("filename", source);
                mailSender.send(mimeMessageHelper.getMimeMessage());

/

import javax.activation.DataSource;

    public class ByteArrayDataSource implements DataSource {
        byte[] bytes;
        String contentType;
        String name;

        public ByteArrayDataSource( String name, String contentType, byte[] bytes ) {
          this.name = name;
          this.bytes = bytes;
          this.contentType = contentType;
        }

        public String getContentType() {
          return contentType;
        }

        public InputStream getInputStream() {
          return new ByteArrayInputStream(bytes);
        }

        public String getName() {
          return name;
        }

        public OutputStream getOutputStream() throws IOException {
          throw new FileNotFoundException();
        }
      }
juud5qan

juud5qan5#

具体的工作示例包括:

1)附件为InputStreamSource接口

public void send() throws IOException, MessagingException {
    final ByteArrayOutputStream stream = createInMemoryDocument("body");
    final InputStreamSource attachment = new ByteArrayResource(stream.toByteArray());
    final MimeMessage message = javaMailSender.createMimeMessage();
    final MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setSubject("subject");
    helper.setFrom("from@from.com");
    helper.setTo("to@to.com");
    helper.setReplyTo("replyTo@replyTo.com");
    helper.setText("stub", false);
    helper.addAttachment("document.txt", attachment);
    javaMailSender.send(message);
}

2)附件为DataSource接口

public void send() throws IOException, MessagingException {
        final ByteArrayOutputStream document = createInMemoryDocument("body");
        final InputStream inputStream = new ByteArrayInputStream(document.toByteArray());
        final DataSource attachment = new ByteArrayDataSource(inputStream, "application/octet-stream");
        final MimeMessage message = javaMailSender.createMimeMessage();
        final MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setSubject("subject");
        helper.setFrom("from@from.com");
        helper.setTo("to@to.com");
        helper.setReplyTo("replyTo@replyTo.com");
        helper.setText("stub", false);
        helper.addAttachment("document.txt", attachment);
        javaMailSender.send(message);
    }

解释:

传入的资源包含开放流:无效参数。JavaMail需要一个InputStreamSource来为每个调用创建一个新的流。

如果开发人员使用在isOpen()方法中返回trueInputStreamSource实现,则可能会出现此消息。

方法MimeMessageHelper#addAttacment()中有一个特殊检查:

public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource, String contentType) {
    //...
    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.");
    }
    //...
}

InputStreamResource#isOpen()始终返回true,这使得无法将此实现用作附件:

public class InputStreamResource extends AbstractResource {
   //...
   @Override
   public boolean isOpen() {
      return true;
   }
   //...
}

相关问题