使用Velocity模板在电子邮件发送中进行编码

时间:2018-07-27 14:37:53

标签: spring encoding character-encoding velocity

我正在使用俄语中的速度模板发送电子邮件,收到的邮件带有垃圾字符。

邮件模板。

 <html>
<body>
<h3>Dear ${name},
    <br/>Greetings from ${companyName}.</h3>

<span>Your Subscription will expire on : ${expiryDate}</span><br/>
<span>Нажмите <a href=${homePageUrl}>здесь</a>, чтобы войти.</span><br/>
<span>Click <a href=${homePageUrl}>here</a> to login.</span><br/>
<h3>Regards, <br/>
    ${companyName}</h3>
</body>
</html>

接收邮件:-

  
    

亲爱的Deepesh,.....的问候。您的订阅将于以下时间过期:23-04-2029 Ru ??????? ??????,?????     ??????点击此处登录。此致,花花公子学习

  

俄罗斯部分是垃圾。

现在我的电子邮件发送代码。

SendEmailResponse response = null;
    try {
        VelocityContext velocityContext = new VelocityContext();
        final Map<String, String> contextMap = request.getContextMap();
        for(Map.Entry<String,String> entry : contextMap.entrySet()) {
            velocityContext.put(entry.getKey(), entry.getValue());
        }

        StringWriter stringWriter = new StringWriter();
        velocityEngine.mergeTemplate("/templates/" + contextMap.get("templateName"),"UTF-8", velocityContext, stringWriter);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setFrom(KP_DEV_MAIL_RU);
        mimeMessageHelper.setTo(contextMap.get("email"));
        mimeMessageHelper.setSubject(contextMap.get("subject"));
        mimeMessageHelper.setText(stringWriter.toString(), true);

    /*FileSystemResource file = new FileSystemResource(new File("banner.jpg"));
    mimeMessageHelper.addInline("banner", file);

    FileSystemResource fileSystemResource = new FileSystemResource(new File("Attachment.jpg"));
    mimeMessageHelper.addAttachment("Attachment.jpg", fileSystemResource);*/

        InputStreamSource source = new ByteArrayResource(request.getFile().toByteArray());
        mimeMessageHelper.addAttachment("Invoice.pdf", source );
        if(LMSCommonUtils.matchEmail(contextMap.get("email"))) {
            javaMailSender.send(mimeMessage);
        }

    }catch (Exception e) {
        LOGGER.error("Error while sending invoice",e);
        res
    }

1 个答案:

答案 0 :(得分:1)

我相信javamailsender也应该配置UTF8。尝试如下

javaMailSender.setDefaultEncoding("UTF-8");