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
}
Related
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!
I have a web scraper written in C# for extracting data. I want to copy text from the web browser control and paste it into a Word file programmatically. When I try to extract rich text box content using its ID and InnerText, the text contains encoded characters like %2c.
I need to get the text with all formatting but I can't find any way. I have tried Encoding, HTTPUtility.UrlDecode, SendKeys and elem.InvokeMember() without success.
How can I programmatically copy and paste text from web browser control preserving formatting?
Here is the sample data to extract:
Description
The Advance Concepts Engineering team designs and develops new vehicles which will meet future regulatory requirements and customer competitive requirements. A qualified candidate will be responsible for the total vehicle packaging. The candidate will identify and resolve adaptation and packaging issues as the vehicle moves toward production. They will lead cross functional team meetings working with Systems & Components, Advance Manufacturing, Service, etc. to ensure that the solutions are optimized for all stages of the vehicle's life.
HtmlElement elem = wb.Document.GetElementById("ctl00_contplhDynamic_txtDescrContentHiddenTextarea");
if (elem == null) return;
elem.InvokeMember("Click");
//elem.InvokeMember("Select All");
//elem.InvokeMember("Copy");
SendKeys.SendWait("^a");
SendKeys.SendWait("^c");
Clipboard.Clear();
elem.Focus();
elem.InvokeMember("Right Click");
elem.InvokeMember("Select All");
elem.InvokeMember("Copy");
Clipboard.SetText(elem.InnerText);
string clipbrdText = Clipboard.GetText();
string data = elem.InnerText;
richTextBox1.Text = data;
string temp = System.Web.HttpUtility.UrlDecode(data);
Encoding iso = Encoding.GetEncoding("windows-1252");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(data);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);
The text with "%2c" etc has been encoded. If you are getting the content of a web page, you are decoding the HTML, not the URL. You can use HttpUtility.HtmlDecode, or if you are using .NET 4.0 or above you can also use WebUtility.HtmlDecode - this is available within the System.Net namespace.
You should note that Word does not use HTML for its formatting, so you won't be able to paste HTML tags and expect it to recognise them. i.e. <strong>Description</strong> will not result in bold text if you type that into Word.
EDIT:
It looks like you are mixing two different ways to copy the text in the code you pasted - both SendKeys.SendWait("^c"); and elem.InvokeMember("Copy");. I presume both of these methods work?
I think the problem you are having lies in the way you are getting the text. I see you're using Clipboard.GetText() to get the text. Try specifying that it is formatted text using Clipboard.GetText(TextDataFormat.Rtf) or Clipboard.GetText(TextDataFormat.Html). This should hopefully copy the string preserving the formatting.
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
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"
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.