简体   繁体   中英

JavaMail and linebreaks

What I'm doing is an email template module. I can send successfully but when I read the sent mail the line-breaks disappeared for example this is what I sent:

"
Dear ñ ,


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


                   I am white spaces



"

This is what I received:

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

Take note that the email body came body the database then stored into a pojo.

The test method for sending:

@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();
    }
}

Since you're using html content, you need to use html markup to control the formatting. Just putting in line breaks and whitespace isn't going to do it unless you're willing to use text/plain instead of text/html.

Consider formatting your email as HTML. It sure shot way of maintaining the formatting. Also, you could use the Commons Email library which will remove a lot of the boiler plate code you need to write.

Take a look at this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM