JavaMail帶附件時出錯

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 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())));
流不匹配會導致報錯。通過轉換成對應的流即可解決



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章