Line breaks ignored when sending mail as plain text - c#

I have a text like " Hi, \r\n this is test \r\n Thanks" I am sending the mail using MailMessage class. I have set the "IsBodyHtml" property to false. The issue is that I am receiving mails without line breaks. Can you let me know what I am missing?

Use Environment.NewLinemsdn instead of \r\n.

We had the same problem, but if you define your message all at once in a String, as opposed to a StringBuilder, you can define your message like this:
string message = string.Format(
#"First Line: {0}
Second Line: {1}
ThirdLine: {2}", firstValue, secondValue, thirdValue);
Defining the message body like this, and setting IsBodyHtml = false, will give you the new lines that you want.
Otherwise, use StringBuilder
var sb = new StringBuilder();
sb.AppendLine("FirstLine");
sb.AppendLine("SecondLine");

This is a feature in Outlook, you can turn it off in Outlook. Go to Options - Mail - and under "Message Format" you uncheck "Remove extra line breaks in plain text messages".
Another solution is to add three spaces at the end of each line, when you send the mail. This seems to get Outlook to accept that it is not an extra line break.

If you are reading your mails from Outlook, it may be Outlook that is removing line breaks, thinking they are extra line breaks. Did you try reading your mails from another software - or maybe a webmail?

To be able to incorporate line breaks, rather than just plain test in your mail, you will need to have the body html set to true, I think.

A more tricky reason this may happen that I just had to deal with:
Your mail server manipulates outgoing messages and adds a html version to your otherwise text only message

I was having a similar problem where most of my line breaks were working but one was not. If I hit reply to the email that wasn't showing the line breaks, the original email text below the reply would show the line break (so this indicates it is an outlook issue). I tried the recommended answer of Environment.NewLine and that DID NOT change anything. In my case, adding a period at the end of the statement where I wanted the new line and then putting in a \r\n did the trick. Per a previous link I posted in this discussion, Outlook is using some rules to filter out line feeds and in the question that started this discussion I notice you do not have a period at the end of your sentence.

I was sending E-Mail notification via PowerShell script and also did not get any line breaks when viewing the mail in Outlook.
For me the solution in the .ps1 file was this:
$emailMessage.Body = "First Line" + "`r`n" + "Second Line"

Related

C# AE.Net.Mail Random Carriage Returns in Subject

I have a problem with the email Subject. I always get an email when there is an error somewhere. So when I look at the email, everything seems fine. But when I watch the characteristics off it, I can see a few errors.
For example:
Subject: Text: Alarm Text about an error
For some reason a carriage return and a space at the start of the new line:
It’s still the same Subject again with a carriage return*
As you can see, for some reasons there are carriage returns (CRLF) which are completely random.
What I’ve tried so far is to check when this happens. Found out that it is Random. When I’m trying to read it out (C#), the Subject is technically right. But instead off a carriage return, there is just nothing. To clarify this: the Subject should be like this:
Subject: Text: Alarm Text about an error for some reason a carriage return and a space at the start of the new line: It’s still the same Subject with a carriage return*
But I get it in the Code like this:
Subject: Text: Alarm Text about an errorfor some reason a carriage return and a space at the start of the new line:It’s still the same Subject with a carriage return
As you can see there is just nothing and there should be a space. So far I’ve tried to change the CRLF to space. Which obviously did not work ‘cause there is no carriage return in the Code. Then I tried to change the encoding to base64. Reason for that was:
http://www.kodokmarton.eu/desktop-application-web-programming/41-web-programming/129-random-newline-and-spaces-inserted-in-emails
So then I tried it like this:
How do I encode and decode a base64 string?
So far nothing worked. This is how I read the mails out:
imap = new AE.Net.Mail.ImapClient(mailServer, login, password, AuthMethods.Login, port, ssl);
var msgs = imap.SearchMessages(SearchCondition.Subject("text Subject"));
for (int i = 0; i < msgs.Length; i++)
{
MailMessage msg = new MailMessage();
msg = msgs[i].Value;
string Subject = msg.Subject;
NOTE: I have to fix it in the Code. For some reasons I can not change the way I send Emails or other things. It has to be in the Code.
Thanks for any advice!

Is Lotus notes email client unable to render <br > tag?

I have a weird problem with Lotus Notes 8.5. In my project I am sending meeting invitation to the user. for that, I generate .ics file. Here is how i generate .ics file
var body = "Dear Raj, \n\n How are you? line break is not working \n\n how?";
using (TextWriter writer = File.CreateText("../test.ics"))
{
writer.WriteLine("BEGIN:VCALENDAR");
writer.WriteLine("PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN");
writer.WriteLine("VERSION:2.0");
writer.WriteLine("METHOD:REQUEST");
writer.WriteLine("BEGIN:VEVENT");
writer.WriteLine("ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE:MAILTO:participant#company.com");
writer.WriteLine("ORGANIZER;CN="Organizer":MAILTO:organizer#test.ccc");
writer.WriteLine("(DTSTART:20141231T010000Z");
writer.WriteLine("DTEND:20141231T010000Z");
writer.WriteLine("TRANSP:OPAQUE");
writer.WriteLine("SEQUENCE:0");
writer.WriteLine("UID:Company-interview-123");
writer.WriteLine("DTSTAMP:20141223T232322Z");
writer.WriteLine("SUMMARY:Interview Scheduled for Job");
writer.WriteLine("DESCRIPTION:{0}", body.Replace("\n","<br />"));
//Adding below property actually fixed the issue.
writer.WriteLine("X-ALT-DESC;FMTTYPE=text/html:{0}", body.Replace("\n","<br />"));
writer.WriteLine("LOCATION:Test Location");
writer.WriteLine("PRIORITY:5");
writer.WriteLine("X-MICROSOFT-CDO-IMPORTANCE:1");
writer.WriteLine("CLASS:PUBLIC");
writer.WriteLine("BEGIN:VALARM");
writer.WriteLine("TRIGGER:-PT15M");
writer.WriteLine("ACTION:DISPLAY");
writer.WriteLine("DESCRIPTION:Reminder");
writer.WriteLine("END:VALARM");
writer.WriteLine("END:VEVENT");
writer.WriteLine("END:VCALENDAR");
}
But Lotus email client is displaying the content as such.
its showing
Dear Raj, <br><br> How are you? line break is not working <br><br> how?
On all other email clients, my content is displaying as
Dear Raj,
How are you? line break is not working
how?
Am i missing something here?
Updated my .ics generation code to add X-ALT-DESC;FMTTYPE=text/html: to fix the issue
I just checked with a vcard that contains your Text in Lotus Notes 8.5 and IBM Notes 9, and it worked exactly as expected. BUT: It worked with your "original" Text without the replace. In the RFC2445 it states, that Line- Breaks have to be encoded as \n:
An intentional formatted text line break MUST only be included in a
"TEXT" property value by representing the line break with the
character sequence of BACKSLASH (US-ASCII decimal 92), followed by a
LATIN SMALL LETTER N (US-ASCII decimal 110) or a LATIN CAPITAL LETTER
N (US-ASCII decimal 78), that is "\n" or "\N".
That means: use
writer.WriteLine("DESCRIPTION:{0}", body);
instead of
writer.WriteLine("DESCRIPTION:{0}", body.Replace("\n","<br>"));
And your problem should be solved
The DESCRIPTION property is not meant to contain any rich text/html content but only plain text.
Lotus Notes may use some other property (X- property) to convey rich text description. Or it may use an ALTREP parameter on the DESCRIPTION, that point to another MIME bodypart in the invitation. See https://www.rfc-editor.org/rfc/rfc5545#section-3.2.1
So what you probably want to do is to send an invitation containing rich text from Lotus Notes to some external account, and then see what the MIME message that you receive looks like.

System.Environment.Newline intermittently not working

I have some code that sends an email.
The code is generally along the lines of :
Stringbuilder sb = new StringBuilder();
sb.Append("Field1:" + Field1.Text);
sb.Append(System.Environment.NewLine);
.
.
.
The string is built, then converted to a string and passed to a function that sends the email.
This works for most of the fields in the form. However, there are a couple of fields that never get a line break. It's really weird that the same code is behaving differently.
I've read there are numerous ways to add a newline in a stringBuilder, and I've also tried
sb.AppendLine()
But that didn't work either.
Suggestions?
Various mail clients will try to mess around with emails to try to make them look more like they think you want them to.
One common example is that sometimes plain text emails are artificially line broken in the sending process after a certain number of characters and a mail client might try to detect this and strip out those artificial line breaks. Most often it will do this by thinking that a single line break is a "fake" and that a double line break represents a new paragraph and should be preserved.
The best way around this is to send mail as HTML. Mail clients may have settings to turn off this undesired behaviour but there is no way to disable it in the mail itself as far as I am aware.
Use an HTML line break tag. Make sure the email is set to allow HTML.
Stringbuilder sb = new StringBuilder();
sb.Append("Field1:" + Field1.Text);
sb.AppendLine("<br />"); //use AppendLine so that source looks pretty. Use HTML break so that the rendered text has a new line
public static void SendMail(MailMessage mail)
{
mail.IsBodyHtml=true;
//send the email
}

Read Text file and Email in Plain Text without affecting the original Text

I have a plain text file that I need to read in using C#, manipulate it a bit then I need to email it. That's easy enough, but it also has to stay in the same format as it's original state:
This is an excerpt from a sample file "mySample.txt":
*****************************NB!!!!**********************************
*Please view http://www.sdfsdf.comsdfsdfsdf . *
*********************************************************************
*** DO NOT DELETE or ALTER ANY OF THE FOLLOWING TEXT ***
Company X PTY.
Lorem Ipsum Office
Last Change - 01 February 2008
APPLICATION TO ESTABLISH A COMMUNITY WITHIN
THE RESTIN DISTRICT OF THE IPSUM.
===================================================================
1. COMMUNITY and ACTION
Give the name of the community. This is the name that will be
used in tables and lists associating the community with the name
district and community forum. The community names that are
delegated by Lorem are at the district level
The Action field specifies whether this is a 'N'ew application, an
'U'pdate or a 'R' removal.
1a. Complete community name:**{0}**
1b. Action - [N]ew, [U]pdate, or [R]emoval :**{1}**
As you can see I've got place holders {0} and {1} in the file which is to be replaced by an automated process.
In my C# I'm using a stream reader to read the entire file into a StringBuilder object then replacing the place holders using the StringBuilder.AppendFormat method.
The problem is when I add the text to a email message body and send it the format ends up looking different. It looks like a bunch of spaces or tabs get removed in the process.
private void Submit_Click(object sender, EventArgs e)
{
//create mail client
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(ConfigurationManager.AppSettings["SubmitToEmail"]);
message.Bcc.Add("xyz#test.com");
message.Subject = "Test Subject";
message.BodyEncoding = Encoding.ASCII;
message.IsBodyHtml = false;
message.Body = _PopulateForm(_GatherInput());//calls method to read the file and replace values
client.Send(message);
//cleanup
client = null;
message.Dispose();
message = null;
}
Anyone have any ideas on how to keep the formatting in tact?
Thanks,
Jacques
The problem you've got is that you're sending plain text as HTML. It's natural that the layout gets changed because HTML is displayed differently than text. Plain text has new lines (\n), tabs (\t), etc., while HTML has line breaks (<BR>) and different layout methods.
If I were you, I would 1st start out by replacing new lines with <BR> (there should be a replace function x.Replace("\n", "<BR>");)
As for the text items that are centered, wrap them in <p style="text-align:center" }>, </p>.
The answer seems to have been with .net and the Mail message object. Instead of adding the content to the Body property, you have to create an alternateView object and add it to that. That solved my problem.
Regards,
Jacques

MailMessage.Body loses CrLf with Encoding.UTF8

I had an interesting bug today when sending plain text emails from our system. We format messages like this:
-1st something happened blab bla.
-2nd something else happened blab blab blaa bla.
Today we had an email that looked like this:
-1st something happened blab bla.
-2nd something else happened blab blab blaa bla $1000.00 -3rd Something happened.
So above, we see that we lost the CrLf but only on the message that didn't have a period and ended in 0. I went through the code and found the CrLf is intack up until we send the email. I tracked the code down below, I am guessing it applies to C# as well:
NOTE: We use Environment.NewLine when building the string for the body.
Building the string:
If Not errorList Is Nothing Then
If errorList.Count > 0 Then
strBldrBody.Append(EMailHelper.CrLf)
strBldrBody.Append(EMailHelper.CrLf)
strBldrBody.Append("Response Error List:")
For Each itm As String In errorList
strBldrBody.Append(EMailHelper.CrLf)
strBldrBody.Append(DataHelper.DASH)
strBldrBody.Append(itm)
Next
End If
End If
Email encoding setting:
Try
If Not String.IsNullOrEmpty(recipient) Then
Using mailMsg As MailMessage = New MailMessage()
mailMsg.From = New MailAddress(_configHelper.EmailFrom)
mailMsg.Subject = subject
mailMsg.Body = body
mailMsg.BodyEncoding = Encoding.UTF8
EMailHelper.SetToAddress(recipient, mailMsg)
Dim smtpClient As SmtpClient = New SmtpClient(_configHelper.EmailRelayServer)
smtpClient.Send(mailMsg)
End Using
End If
Catch ex As System.Exception
'logs error
End Try
I want to know what happened in the string translation during the UTF-8 encoding/decoding that removes the CrLf?!
The problem was Outlook, see below:
outlook screen shot
We just had a problem similar to this, but it turned out to be a conversion we did from a bytestream to a string. I have also seen this happen when getting encodings mixed up. From the code posted, I don't see how this could happen.
Oh, and to Hans - he meant 'intact' not 'in tack'
You say that the message is intact (including that newline) up to the point where you send the message, but when the message was received it didn't contain the newline? Can you duplicate this error?
Whereas it's possible that the SmtpClient control somehow lost the newline, it's also possible that one of the relay servers lost it in translation somewhere, or that your email client didn't render it correctly.
Messages go through an incredible number of different translation steps between servers, and some of those translations are ... less than rigorously debugged. In particular, the quoted-printable encoding has some interesting edge cases that lots of implementations don't get correct.
If your relay server is local, I would suggest turning on logging so that it will save a copy of the message as it's received from you. And on the receiving end, get the actual bits of the message (if possible), without any kind of translation by client software.

Categories

Resources