【问题标题】:UTF-8 characters in Java Email with Excel as attachment使用 Excel 作为附件的 Java 电子邮件中的 UTF-8 字符
【发布时间】: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


    【解决方案1】:

    试试这个 项目 -> 属性并将“文本文件编码”更改为 UTF-8

    【讨论】:

    • 我在 Eclipse 中找不到这个选项。
    • 在资源部分下的属性中,可以使用
    猜你喜欢
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2015-02-10
    • 2013-04-21
    • 2022-01-09
    相关资源
    最近更新 更多