Reputation: 3439
I want to send a pdf file in an email with javax mail.
Below, baos is a ByteArrayOutputStream.
byte [] data= baos.toByteArray();
OutputStream output = new FileOutputStream(fileName);
output.write(data);
output.close();
DataSource source = new FileDataSource(fileName);
attachBodyPart.setDataHandler(new DataHandler(source, "application/pdf"));
attachBodyPart.setFileName(fileName);
multipart.addBodyPart(attachBodyPart);
message.setContent(multipart, "text/html");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
I am getting this exception when I try to send the email :
javax.mail.MessagingException: IOException while sending message;
nested exception is: javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/pdf
I don't know what's wrong here.
If someone does...
Thanks in advance.
Upvotes: 5
Views: 7118
Reputation: 1435
I am also using FileDataSource. Since DataHandler had issues with this data source, I had to use own implementation of DataHandler:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
public class FileDataHandler extends DataHandler{
private final File file;
public FileDataHandler(File file, String contentType) {
super(new FileDataSource(file), contentType);
this.file = file;
}
@Override
public void writeTo(OutputStream os) throws IOException {
try (InputStream is = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(is)) {
byte data[] = new byte[8 * 1024];
int bytes_read;
while ((bytes_read = bis.read(data)) > 0) {
os.write(data, 0, bytes_read);
}
}
}
}
In your case it is simple to create this FileDataHandler directly ignoring DataSource.
Upvotes: 0
Reputation: 1791
Try this.
MimeBodyPart attachment = new MimeBodyPart();
DataSource dataSrc = new ByteArrayDataSource(baos.toByteArray(), "application/pdf");
attachment.setDataHandler(new DataHandler(dataSrc));
attachment.setFileName("myPdfDocument.pdf");
multipart.addBodyPart(attachment);
Upvotes: 5
Reputation: 13858
Everytime I do this I use byte array directly without working through file:
byte [] data = baos.toByteArray();
MimeBodyPart attachBodyPart = new MimeBodyPart();
attachBodyPart.setFileName(fileName);
attachBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
attachBodyPart.setContent(data, "application/pdf");
multipart.addBodyPart(attachBodyPart);
Upvotes: 0