[java] How do I format a String in an email so Outlook will print the line breaks?

I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook.

I found a page on microsoft.com that says there's a 'Remove line breaks' "feature" in Outlook so does this mean there's no solution to get around that other than un-checking that setting?

Thanks

This question is related to java email outlook newline line-breaks

The answer is


\r\n will not work until you set body type as text.

message.setBody(MessageBody.getMessageBodyFromText(msg));
BodyType type = BodyType.Text;
message.getBody().setBodyType(type);

You can force a line break in outlook when attaching one (or two?) tab characters (\t) just before the line break (CRLF).

Example:

This is my heading in the mail\t\n
Just here Outlook is forced to begin a new line.

It seems to work on Outlook 2010. Please test if this works on other versions.

See also Outlook autocleaning my line breaks and screwing up my email format


The \n largely works for us, but Outlook does sometimes take it upon itself to remove the line breaks as you say.


For Outlook 2010 and later versions, use \t\n rather than using \r\n.


I've just been fighting with this today. Let's call the behavior of removing the extra line breaks "continuation." A little experimenting finds the following behavior:

  • Every message starts with continuation off.
  • Lines less than 40 characters long do not trigger continuation, but if continuation is on, they will have their line breaks removed.
  • Lines 40 characters or longer turn continuation on. It remains on until an event occurs to turn it off.
  • Lines that end with a period, question mark, exclamation point or colon turn continuation off. (Outlook assumes it's the end of a sentence?)
  • Lines that turn continuation off will start with a line break, but will turn continuation back on if they are longer than 40 characters.
  • Lines that start or end with a tab turn continuation off.
  • Lines that start with 2 or more spaces turn continuation off.
  • Lines that end with 3 or more spaces turn continuation off.

Please note that I tried all of this with Outlook 2007. YMMV.
So if possible, end all bullet items with a sentence-terminating punctuation mark, a tab, or even three spaces.


Because it is a query, only percent escaped characters work, means %0A gives you a line break. For example,

<a href="mailto:[email protected]?Subject=TEST&body=Hi there,%0A%0AHow are you?%0A%0AThanks">email to me</a>

You need to send HTML emails. With <br />s in the email, you will always have your line breaks.


RESOLVED IN MY APPLICATION

In my application, I was trying to send an email whose message body was typed by the user in text area. When mail was send, outlook automatically removed line break entered by user.

e.g if user entered
Yadav
Mahesh

outlook displayed it as
YadavMahesh

Resolution: I changed the line break character "\r\n" with "\par " ( remember to hit space at the end of RTF code "\par" )and line breaks are restrored.

Cheers,
Mahesh


Adding "\t\r\n" ( \t for TAB) instead of "\r\n" worked for me on Outlook 2010 . Note : adding 3 spaces at end of each line also do same thing but that looks like a programming hack!


Sometimes you have to enter \r\n twice to force outlook to do the break.

This will add one empty line but all the lines will have break.


I also had this issue with plain/text mail type. Earlier, I used "\n\n" but there was two line breaks. Then, I used "\t\n" and it worked. I was using StringBuffer in java to append content.
The content got printed in next line in Outlook 2010 mail.


The trick is to use the encodeURIComponent() functionality from js:

var formattedBody = "FirstLine \n Second Line \n Third Line";
var mailToLink = "mailto:[email protected]?body=" + encodeURIComponent(formattedBody);

RESULT:

FirstLine
SecondLine
ThirdLine

I was facing the same issue and here is the code that resolved it:

\t\n - for new line in Email service JavaMailSender

String mailMessage = JSONObject.toJSONString("Your message").replace(",", "\t\n").trim();

If you can add in a '.' (dot) character at the end of each line, this seems to prevent Outlook ruining text formatting.


I had the same issue, and found a solution. Try this: %0D%0A to add a line break.


I also had this issue with plain/text mail type.Form Feed \f worked for me.


Put the text in <pre> Tags and outlook will format and display the text correctly.

i defined it in CSS inline in HTML Body like:

CSS:

pre {
 font-family: Verdana, Geneva, sans-serif;
}

i defined the font-family to have to font set.

HTML:

<td width="70%"><pre>Entry Date/Time:       2013-09-19 17:06:25
Entered By:     Chris

worklog mania

____________________________________________________________________________________________________

Entry Date/Time:        2013-09-19 17:05:42
Entered By:     Chris

this is a new Worklog Entry</pre></td>

Microsoft Outlook 2002 and above removes "extra line breaks" from text messages by default (kb308319). That is, Outlook seems to simply ignore line feed and/or carriage return sequences in text messages, running all of the lines together.

This can cause problems if you're trying to write code that will automatically generate an email message to be read by someone using Outlook.

For example, suppose you want to supply separate pieces of information each on separate lines for clarity, like this:

Transaction needs attention!
PostedDate: 1/30/2009
Amount: $12,222.06
TransID: 8gk288g229g2kg89
PostalCode: 91543

Your Outlook recipient will see the information all smashed together, as follows:

Transaction needs attention! PostedDate: 1/30/2009 Amount: $12,222.06 TransID: 8gk288g229g2kg89 ZipCode: 91543

There doesn't seem to be an easy solution. Alternatives are:

  1. You can supply two sets of line breaks between each line. That does stop Outlook from combining the lines onto one line, but it then displays an extra blank line between each line (creating the opposite problem). By "supply two sets of line breaks" I mean you should use "\r\n\r\n" or "\r\r" or "\n\n" but not "\r\n" or "\n\r".
  2. You can supply two spaces at the beginning of every line in the body of your email message. That avoids introducing an extra blank line between each line. But this works best if each line in your message is fairly short, because the user may be previewing the text in a very narrow Outlook window that wraps the end of each line around to the first position on the next line, where it won't line up with your two-space-indented lines. This strategy has been used for some newsletters.
  3. You can give up on using a plain text format, and use an html format.

I had been struggling with all of the above solutions and nothing helped here, because I used a String variable (plain text from a JTextPane) in combination with "text/html" formatting in my e-mail library.

So, the solution to this problem is to use "text/plain", instead of "text/html" and no need to replace return characters at all:

MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/plain");

Try this:

message.setContent(new String(body.getBytes(), "iso-8859-1"),
                    "text/html; charset=\"iso-8859-1\"");

Regards, Mohammad Rasool Javeed


I have used html line break instead of "\n" . It worked fine.


Microsoft Outlook 2002 and above removes "extra line breaks" from text messages by default (kb308319). That is, Outlook seems to simply ignore line feed and/or carriage return sequences in text messages, running all of the lines together.

This can cause problems if you're trying to write code that will automatically generate an email message to be read by someone using Outlook.

For example, suppose you want to supply separate pieces of information each on separate lines for clarity, like this:

Transaction needs attention!
PostedDate: 1/30/2009
Amount: $12,222.06
TransID: 8gk288g229g2kg89
PostalCode: 91543

Your Outlook recipient will see the information all smashed together, as follows:

Transaction needs attention! PostedDate: 1/30/2009 Amount: $12,222.06 TransID: 8gk288g229g2kg89 ZipCode: 91543

There doesn't seem to be an easy solution. Alternatives are:

  1. You can supply two sets of line breaks between each line. That does stop Outlook from combining the lines onto one line, but it then displays an extra blank line between each line (creating the opposite problem). By "supply two sets of line breaks" I mean you should use "\r\n\r\n" or "\r\r" or "\n\n" but not "\r\n" or "\n\r".
  2. You can supply two spaces at the beginning of every line in the body of your email message. That avoids introducing an extra blank line between each line. But this works best if each line in your message is fairly short, because the user may be previewing the text in a very narrow Outlook window that wraps the end of each line around to the first position on the next line, where it won't line up with your two-space-indented lines. This strategy has been used for some newsletters.
  3. You can give up on using a plain text format, and use an html format.

Try \r\c instead of \n.

EDIT: I think @Robert Wilkinson had it right. \r\n. Memory just isn't what it used to be.


if the message is text/plain using, \r\n should work; if the message type is text\html, use < p/>


I have a good solution that I tried it, it is just add the Char(13) at end of line like the following example:

Dim S As String
 S = "Some Text" & Chr(13)
 S = S + "Some Text" & Chr(13)

Not sure if it was mentioned above but Outlook has a checkbox setting called "Remove extra line breaks in plain text messages" and is checked by default. It is located in a different spot for different versions of Outlook but for 2010 go to the "File" tab. Select "Options => Mail" Scroll down to "Message format" Uncheck the checkbox.


if work need to be done with formatted text with out html encoding. it can be easy achieved with following scenario that creates div element on the fly and using <pre></pre> html element to keep formatting.

var email_body = htmlEncode($("#Body").val());

 function htmlEncode(value) {
    return "<pre>" + $('<div/>').text(value).html() + "</pre>";
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to email

Monitoring the Full Disclosure mailinglist require(vendor/autoload.php): failed to open stream Failed to authenticate on SMTP server error using gmail Expected response code 220 but got code "", with message "" in Laravel How to to send mail using gmail in Laravel? Laravel Mail::send() sending to multiple to or bcc addresses Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate How to validate an e-mail address in swift? PHP mail function doesn't complete sending of e-mail How to validate email id in angularJs using ng-pattern

Examples related to outlook

Does VBA contain a comment block syntax? "Sub or Function not defined" when trying to run a VBA script in Outlook Change HTML email body font type and size in VBA css padding is not working in outlook Image style height and width not taken in outlook mails Paste Excel range in Outlook MS Access VBA: Sending an email through Outlook HTML email in outlook table width issue - content is wider than the specified table width Save attachments to a folder and rename them Sending email from Command-line via outlook without having to click send

Examples related to newline

How can I insert a line break into a <Text> component in React Native? Print "\n" or newline characters as part of the output on terminal Using tr to replace newline with space How to write one new line in Bitbucket markdown? Line break in SSRS expression How to insert a new line in Linux shell script? Replace CRLF using powershell How to write new line character to a file in Java What is the newline character in the C language: \r or \n? How to print values separated by spaces instead of new lines in Python 2.7

Examples related to line-breaks

HTML5 tag for horizontal line break Split string in JavaScript and detect line break Match linebreaks - \n or \r\n? How to linebreak an svg text within javascript? What is the difference between a "line feed" and a "carriage return"? Bash: Strip trailing linebreak from output How to read a file without newlines? How to break lines in PowerShell? How do I specify new lines on Python, when writing on files? How to remove line breaks (no characters!) from the string?