【发布时间】:2020-10-31 06:09:56
【问题描述】:
我正在开发一个遗留应用程序,在该应用程序中,我必须在电子邮件正文和附件(Excel、xls 文件)中发送带有特殊字符 (utf-8) 的电子邮件。
我在这方面做了很多尝试。特殊字符在附件 xls 文件中未正确显示,但在电子邮件正文中显示正确。
我使用的代码 sn-p 如下。
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..");
}
带有特殊字符的邮件正文:
带有特殊字符的邮件附件 XLS 文件,我确实在附加的 xls 文件中添加了相同的 html 正文数据。
请帮助我如何实现这一点,以正确显示附件中的特殊字符。
【问题讨论】:
标签: java excel email utf-8 email-attachments