JavaMail和换行符

时间:2014-01-02 01:17:01

标签: java java-ee javamail line-breaks

我正在做的是一个电子邮件模板模块。我可以成功发送但是当我读取已发送的邮件时,换行符消失了,例如这就是我发送的内容:

"
Dear ñ ,


                     ABCDEFGHIJKLMNOPQRSTUVWXYZ. abcdefghijklmnopqrstuvwxyz. 1234567890. !@#$%^&*()_. Loren ipsum blahbity blahbity blah blah. WQWERTYUIOP{}ASDFGHJKL"ZXCVBNM<>


                   I am white spaces



"

这是我收到的:

"Dear ñ , ABCDEFGHIJKLMNOPQRSTUVWXYZ. abcdefghijklmnopqrstuvwxyz. 1234567890. !@#$%^&*()_. Loren ipsum blahbity blahbity blah blah.QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<> I am white spaces"

请注意,电子邮件正文是数据库的主体,然后存储到pojo中。

发送的测试方法:

@Test
public void sendServiceTest() {
    String hostName = null;
    // Set up the SMTP server.
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", getHost);

    Session session = Session.getDefaultInstance(props);
    session.setDebug(true);

    Message msg = new MimeMessage(session);

    try {
        hostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        msg.setFrom(new InternetAddress(hostName));
        InternetAddress manyAddressTo = null;
        // InternetAddress[] manyAddressCC = null;
        // InternetAddress[] manyAddressBCC = null;
        List<EmailRecipient> recipients = emailRecipientService
                .selectRecipientByCode("E1");

        manyAddressTo = new InternetAddress("sample@sample.com");

        msg.setRecipient(Message.RecipientType.TO, manyAddressTo);
        msg.setSubject(recipients.get(0).getEmailTemplate().getSubject());

        msg.setContent(recipients.get(0).getEmailTemplate().getEmail_body()+"\r\n","text/html; charset=utf-8");
        Transport.send(msg);

    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:2)

由于您使用的是html内容,因此需要使用html标记来控制格式。除非你愿意使用text / plain而不是text / html,否则只是放入换行符和空格不会这样做。

答案 1 :(得分:1)

考虑将您的电子邮件格式化为HTML。它肯定会保持格式化的方式。此外,您可以使用Commons Email库,它将删除您需要编写的许多样板代码。

看看这个

http://commons.apache.org/proper/commons-email/userguide.html