我编写了实现DataSource的自定义类,将InputStream转换为DataHandler。我用它来发送邮件附件。但附件现在显示无效内容。
以下是自定义类实现:
public class InputStreamDataSource implements DataSource {
private InputStream inputStream;
public InputStreamDataSource(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public InputStream getInputStream() throws IOException {
return inputStream;
}
@Override
public OutputStream getOutputStream() throws IOException {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public String getContentType() {
return "*/*";
}
@Override
public String getName() {
return "InputStreamDataSource";
}
}
用于发送邮件功能的代码:
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates body part for the attachment
MimeBodyPart attachPart = new MimeBodyPart();
String attachFile = attachment.getName();
InputStream ipStream=null;
ipStream = attachment.getInputStream();
DataHandler dataHandler = new DataHandler(new InputStreamDataSource(ipStream));
attachPart.setDataHandler(dataHandler);
attachPart.setFileName(attachFile);
// adds parts to the multipart
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachPart);
msg.setContent(multipart);
Transport.send(msg);