Search code examples
javaspring-bootemail

SpringBoot.- send message with Carriage Return


I want to send a message with Carriage Return, with it send it as 1 line

public static void main(String[] args) throws MessagingException {

    Properties prop = new Properties();

    prop.put("mail.smtp.auth", true);
    prop.put("mail.smtp.starttls.enable", "true");
    prop.put("mail.smtp.host", "smtp.suerviciodecorreo.es");
    prop.put("mail.smtp.port", "588");
    prop.put("mail.smtp.ssl.trust", "smtp.suerviciodecorreo.es");

   
    String mailTo = "[email protected]";
    String from = "[email protected]";
    String subject = "hola ? ";
    String body = "Saludos\\r\\n" +
            "\n" +
            " \n" +
            "\n" +
            " \n" +
            "\n" +
            "aaaaa\\r\\n" +
            "\n" +
            "bbbbbb\n" +
            "\n" ;

    //log.info("Sending email to: *{}* ", mailTo);

    Session session = Session.getInstance(prop, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("[email protected]", "Eiu8hhuy72024");
        }

    });

    //log.info("Sending email to1: " + mailTo);

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("[email protected]"));

    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTo));
    message.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(body, "text/html; charset=utf-8");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);


    log.info("Setting content");

    message.setContent(multipart);

    log.info("Sending message {} ", message);

    Transport.send(message);

    log.info("Sent message {}", message);

}

Solution

  • In Java, the sequence \\r\\n will be interpreted as a literal backslash followed by r and n, not as carriage return and line feed. You need to use \r\n directly in your string for the carriage return and line feed characters.

    Here is the corrected version of your string:

    String body = "Saludos\r\n" +
              "\n" +
              " \n" +
              "\n" +
              " \n" +
              "\n" +
              "aaaaa\r\n" +
              "\n" +
              "bbbbbb\n" +
              "\n";
    
    Use \r\n for carriage return and line feed.
    Use \n for a line feed (newline).