你如何发送带有中文字符的Javamail?

时间:2014-01-22 23:19:10

标签: java servlets character-encoding javamail

我编写了servlet类并发送邮件类来发送Javamail。英文信息很好,但现在我也想发送中文。我想你在MimeMessage的setSubject和setText方法中添加了UTF-8。我做到了,但所有中文字符都在我的收件箱中损坏了。

电子邮件来自用户输入的提交表单。

这是我的servlet:

package com.lsp.web;

import com.lsp.service.Mailer;
import org.springframework.beans.factory.annotation.Autowired;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "contact", urlPatterns = {"/contact"})
public class ContactServlet extends SpringInjectedServlet {
    @Autowired
    private Mailer mailer;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("contact.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String customerEmail = req.getParameter("email");
        String subject = req.getParameter("subject");
        String body = req.getParameter("message");
        String name = req.getParameter("name");

        body = "YOU HAVE A MESSAGE FROM " + name + "<" + customerEmail +">.\n" + body;

        String error = null;
        String succMess = null;

        try {
            javax.mail.internet.InternetAddress ia = new javax.mail.internet.InternetAddress(customerEmail);
            ia.validate();
            mailer.send(customerEmail, subject, body);
            succMess = "你的消息已成功发送";
            req.setAttribute("succMessage", succMess);
            req.getRequestDispatcher("sent.jsp").forward(req, resp);

        } catch (javax.mail.internet.AddressException ae) {
            error = "您指出的邮箱地址不存在";
            req.setAttribute("errorMessage", error);
            req.getRequestDispatcher("contact.jsp").forward(req, resp);
        }
        catch (MessagingException mex) {
            error = "发送失败";
            req.setAttribute("errorMessage", error);
            req.getRequestDispatcher("contact.jsp").forward(req, resp);
        }
    }
}

邮件程序类(发送电子邮件):

package com.lsp.service;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Component
public class Mailer {
    private static final Logger log = Logger.getLogger(Mailer.class);

    public Mailer() {
        log.info("I'm newed.");
    }

    public void send(String custMail, String subject, String body) {
        String from = "jshao745@gmail.com";
        String to = "jshao745@gmail.com";

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");


       //body = "YOU HAVE A MESSEGE FROM " + custMail + "." + body;

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("jshao745@gmail.com","SOMEPASSWORD");//change accordingly
                 }
            });


        try{
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            message.setHeader("Content-Type", "text/plain; charset=UTF-8");

            // Set Subject: header field
            message.setSubject(subject, "UTF-8");

            // Send the actual HTML message, as big as you like
            message.setText(body, "UTF-8");

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

如果有人可以帮助我,我感激不尽。

谢谢。

1 个答案:

答案 0 :(得分:1)

首先,确保您的Java String对象包含正确的Unicode字符。如果你没有正确地进行输入字符转换,你可能会在String对象中结束垃圾,这当然意味着电子邮件中的垃圾。

此外,您不需要显式设置Content-Type标头,setText方法将为您执行此操作。

您可能还想阅读此common JavaMail mistakes列表。