Java:Java邮件拼凑电子邮件主题。

时间:2015-10-01 09:08:26

标签: java email

我以编程方式发送电子邮件,但电子邮件中的主题变得混乱(在下面发布)。谁能告诉我我做错了什么。非常感谢。

发送电子邮件的代码:

final String from = "from@gmail.com";
        final String emailPassword = "password";
        final String to = "somemail@gmail.com";
        final String ccMail = "ccmail@gmail.com";
        String[] mailAddressTo = new String[2];
        mailAddressTo[0] = to;
        mailAddressTo[1] = ccMail;

        InternetAddress[] mailAddress_TO = new InternetAddress[mailAddressTo.length];

        for (int i = 0; i < mailAddressTo.length; i++)
        {
            try {
                mailAddress_TO[i] = new InternetAddress(mailAddressTo[i]);
            } catch (AddressException ignored) {          }
        }

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "25");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator(){
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(
                                from, emailPassword);
                    }
                });
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
            message.addRecipients(Message.RecipientType.TO, mailAddress_TO);
            message.setSubject("Es hat sich jemand für einen Kurs eingeschrieben");
            String messageText = "some text";
            message.setContent(messageText,"text/html;charset=UTF-8");
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

主题输出:

=?ANSI_X3.4-1968?Q?Es_hat_sich_jemand_f=3Fr_einen_Kurs_eingeschrieben?=

以上输出我在邮件客户端和浏览器中也是如此。我究竟做错了什么?

1 个答案:

答案 0 :(得分:3)

这似乎是使用过的字符集的问题。要对此进行测试,您可以尝试在源代码中设置字符编码:

    System.setProperty("mail.mime.charset","Cp1252");

我认为JavaMail API会检查一些属性,但我无法记住这些属性。