简体   繁体   中英

Formatting an email with JavaMail in Java

So I have sent an email in Java, however It doesn't format the email as I'd like. Instead of a formatted email like this:

Hello John,

Welcome to X.

Thanks,

Johnathan.

It would show:

Hello John, Welcome to X. Thanks, Johnathan.

This is the code:

public class MailReceipt {

String receipt;
String email;
public MailReceipt(String message, String email) {
    this.receipt = message;
    this.email = email;

}

public void sendMessage() {

    final String username = "abc123@gmail.com";
    final String password = "abc123";

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

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }

    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, 
                InternetAddress.parse(email));
        message.setSubject("DO NOT REPLY: A receipt regarding your recent purchase.");
        message.setContent(receipt, "text/html; charset=utf-8");
        Transport.send(message);

        System.out.println("The mail was sent");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }












}

}

I am using '\\n' tags in the string, however it doesn't seem to work here. Would I need to make use of html in Java? If so, could I get some examples?

You've said its content-type is HTML, so use HTML. A newline isn't significant in HTML. Try <p> , or <br/> .

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