My application has to send a textfile, which it first has to generate as a String. The text contains non-ASCII symbols, so i would like it to be UTF-8. I\'ve tried a lot of vari
This works:
MimeMessage msg = new MimeMessage(session);
msg.setFrom(sendFrom);
msg.setSubject(subject, "utf-8");
msg.setSentDate(new Date());
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setContent(message,"text/plain; charset=UTF-8");
// mbp1.setContent(message,"text/html; charset=UTF-8"); // with this the attachment will fail
// create the Multipart and its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
if (attachment!=null){
// Part two is attachment
MimeBodyPart mbp2 = new MimeBodyPart();
mbp2 = new MimeBodyPart();
DataSource ds = null;
try {
ds = new ByteArrayDataSource(attachment.getBytes("UTF-8"), "application/octet-stream");
} catch (IOException e) {
e.printStackTrace();
}
mbp2.setDataHandler(new DataHandler(ds));
mbp2.addHeader("Content-Type", "text/plain; charset=\"UTF-8\"");
mbp2.addHeader("Content-Transfer-Encoding", "base64");
mbp2.setFileName("attachment.txt");
mbp2.setDisposition(Part.ATTACHMENT);
mp.addBodyPart(mbp2);
}
// add the Multipart to the message
msg.setContent(mp);
msg.saveChanges();
// send the message
Transport.send(msg);
Set the content type to application/octet-stream:
MimeBodyPart attachmentPart = new MimeBodyPart();
try {
DataSource ds = new ByteArrayDataSource(attachment.getBytes("UTF-8"), "application/octet-stream");
attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(ds));
}
catch (Exception e) {
Logger.getLogger("Blina").log(Level.SEVERE, Misc.getStackTrace(e));
}
attachmentPart.setFileName(fileName);
multipart.addBodyPart(attachmentPart);
// Put parts in message
msg.setContent(multipart);