I'm working on a legacy application in which i have to send an email with special characters (utf-8) in email body as well as in the attachment (Excel, xls file).
I've tried a lot on this. Special Characters are not shown correctly in the attachment xls file, however in the email body it's shown correctly.
Code snippet that i'm using is as below.
private void initalizeMailSession()
{
java.util.Properties props = new java.util.Properties();
props.setProperty("mail.smtp.host", Properties.MAIL_SMTP_HOST);
mailSession = Session.getInstance(props);
}
public void sendMailUtf8Attachment() throws Exception
{
// Send mail for current object
if(mailSession==null)
initalizeMailSession();
MimeMessage mailMsg = new MimeMessage(mailSession);
InternetAddress recipient=null;
if(toList==null&&ccList==null&&bccList==null)
{
throw new Exception("No Recipents Found");
}
if(toList!=null)
{
for(String toAddress: toList)
{
recipient=new InternetAddress(toAddress);
mailMsg.addRecipient(javax.mail.Message.RecipientType.TO, recipient);
}
}
if(sender==null)
throw new Exception("Sender not found");
InternetAddress sender=new InternetAddress(this.sender);
mailMsg.setFrom(sender);
mailMsg.setSubject(subject);
MimeMultipart mult = new MimeMultipart();
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setContent(mailMessage, mailType);
mult.addBodyPart(messagePart);
MimeBodyPart filePart = new MimeBodyPart();
filePart.setText(message, "UTF-8"); // message string is having html code with Chinese characters in it.
filePart.setDisposition(MimeBodyPart.ATTACHMENT);
filePart.setFileName("attachmen.xls");
filePart.setHeader("Content-Transfer-Encoding", "base64");
filePart.setHeader("Content-Type", HTML);
mult.addBodyPart(filePart);
mailMsg.setContent(mult);
Transport.send(mailMsg);
System.out.println("Mail send..");
}
Mail Body with Special Characters :
Mail Attachment XLS file with Special Characters, I've do add the same html body data in the attached xls file.
Please help how do i achieve this, to correctly show the special characters in the attachment.