Equals sign magically appears in message sending to pager - c#

I am sending a mail to an email address which forwards messages to a pager. The message I am sending is
"Oth info; Thankyou testing now complete just be aware that 34a door
will open and shut when pager messages are sent with the CFSRES lt1".
but client receives it on his pager as
"Oth info; Thankyou testing now complete just be aware that 34a door
will op= en and shut when pager messages are sent with the CFSRES
lt1".
Does anyone know why the equals sign shows up in open changed to op= en. I know that special characters may some times be changed, like spaces can become %20, but open does not contain any special character, so as far as I know, nothing should happen to it.

This is a sign of Quoted-printable encoding
QP works by using the equals sign "=" as an escape character. It also limits line length to 76, as some software has limits on line length.
So you may try to split the message into multiple lines in an attempt to prevent escape characters being added by the forwarder.

I search for net and found the solution, this links solve my problem. Here is some userfull code, i need to provide the CreateAlternateViewFromString.
MailMessage emailmsg = new MailMessage("from#address.co.za", "to#address.co.za")
emailmsg.Subject = "Subject";
emailmsg.IsBodyHtml = false;
emailmsg.ReplyToList.Add("from#address.co.za");
emailmsg.BodyEncoding = System.Text.Encoding.UTF8;
emailmsg.HeadersEncoding = System.Text.Encoding.UTF8;
emailmsg.SubjectEncoding = System.Text.Encoding.UTF8;
emailmsg.Body = null;
var plainView = AlternateView.CreateAlternateViewFromString(EmailBody, emailmsg.BodyEncoding, "text/plain");
plainView.TransferEncoding = TransferEncoding.SevenBit;
emailmsg.AlternateViews.Add(plainView);
SmtpClient sSmtp = new SmtpClient();
sSmtp.Send(emailmsg);

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!

Ae.Net.Mail - IMAP - Get only unseen messages

I have a Windows service using the AE.Net.Mail IMAP client with G-mail. The service runs every x minutes, retrieves inbox messages, applies some business logic, and marks them as deleted. This all works.
However, Gmail leaves them in the inbox so subsequent calls fetch them again. I can skip them by looking at the Seen or Deleted flags but I'd rather not get them at all. Unless someone goes in and cleans up the inbox frequently fetches will grow exponentially.
I've experimented with Gmails expunge options but they don't seem to have any effect.
I know this is a bit old post but just in case anybody is looking for a way to do this can try :
ImapClient ic = new ImapClient("imap.gmail.com", "name#gmail.com", "pass", AuthMethods.Login, 993, true);
var mailMessage = ic.SearchMessages(SearchCondition.Unseen(), false, true).ToList();
Now you can loop through the mailMessage for unread email.
I decided to just filter them out when I retrieved them. Not ideal, but it works
List<AE.Net.Mail.MailMessage> mm = _client.GetMessages(0, 10, false, false)
.Where(m => !m.Flags.HasFlag(Flags.Seen)
&& !m.Flags.HasFlag(Flags.Deleted)).ToList();
I know this is a bit old post but just in case anybody is looking for a way to do this can try move:
AE.Net.Mail.Imap.Mailbox[] mailBoxes = client.ListMailboxes(string.Empty, "*");
bool existeMailBoxArquivo = false;
const string ARQUIVO = "ARQUIVO";
foreach (var mailBox in mailBoxes)
{
if (mailBox.Name == ARQUIVO)
existeMailBoxArquivo = true;
}
if (!existeMailBoxArquivo)
client.CreateMailbox(ARQUIVO);
client.MoveMessage(msg.Uid, ARQUIVO);
So you move the messages to a file folder, and when you browse again, just select the main box to search

Split string with response from gmail

After I retrieve messages from mail box I want to separate message body from subject, date and other information. But I can't find wright algorithm. Here is my code:
// create an instance of TcpClient
TcpClient tcpclient = new TcpClient();
// HOST NAME POP SERVER and gmail uses port number 995 for POP
tcpclient.Connect("pop.gmail.com", 995);
// This is Secure Stream // opened the connection between client and POP Server
System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());
// authenticate as client
sslstream.AuthenticateAsClient("pop.gmail.com");
//bool flag = sslstream.IsAuthenticated; // check flag
// Asssigned the writer to stream
System.IO.StreamWriter sw = new StreamWriter(sslstream);
// Assigned reader to stream
System.IO.StreamReader reader = new StreamReader(sslstream);
// refer POP rfc command, there very few around 6-9 command
sw.WriteLine("USER my_login");
// sent to server
sw.Flush();
sw.WriteLine("PASS my_pass");
sw.Flush();
// this will retrive your first email
sw.WriteLine("RETR 1");
sw.Flush();
string str = string.Empty;
string strTemp = string.Empty;
while ((strTemp = reader.ReadLine()) != null)
{
// find the . character in line
if (strTemp == ".")
{
break;
}
if (strTemp.IndexOf("-ERR") != -1)
{
break;
}
str += strTemp;
}
// close the connection
sw.WriteLine("Quit ");
sw.Flush();
richTextBox2.Text = str;
I have to extract:
The subject of message
The author
The date
The message body
Can anyone tell me how to do this?
String which I receive (str) contains the subject Test message and the body This is the text of test message. It looks like:
+OK Gpop ready for requests from 46.55.3.85 s42mb37199022eev+OK send PASS+OK Welcome.+OK message followsReturn-Path:
Received: from TMD-I31S3H51L29
(host-static-46-55-3-85.moldtelecom.md. [46.55.3.85]) by
mx.google.com with ESMTPSA id o5sm61119999eeg.8.2014.04.16.13.48.20
for (version=TLSv1
cipher=ECDHE-RSA-AES128-SHA bits=128/128); Wed, 16 Apr 2014
13:48:21 -0700 (PDT)Message-ID:
<534eec95.856b0e0a.55e1.6612#mx.google.com>MIME-Version: 1.0From:
mail_address#gmail.comTo: mail_address#gmail.comDate: Wed, 16 Apr 2014
13:48:21 -0700 (PDT)Subject: Test messageContent-Type: text/plain;
charset=us-asciiContent-Transfer-Encoding: quoted-printableThis is the
text of test message
Thank you very much!
What you first need to do is read rfc1939 to get an idea of the POP3 protocol. But immediately after reading that, you'll need to read the following list of RFCs... actually, screw it, I'm not going to paste the long list of them here, I'll just link you to the website of my MimeKit library which already has a fairly comprehensible list of them.
As your original code correctly did, it needs to keep reading from the socket until the termination sequence (".\r\n") is encountered, thus terminating the message stream.
The way you are doing it is really inefficient, but whatever, it'll (mostly) work except for the fact that you need to undo any/all byte-stuffing that is done by the POP3 server to munge lines beginning with a period ('.'). For more details, read the POP3 specification I linked above.
To parse the headers, you'll need to read rfc822. Suffice it to say, Olivier's approach will fall flat on its face, most likely the second it tries to 'split' any real-world messages... unless it gets extremely lucky.
As a hint, the message body is separated from the headers by a blank line.
Here's a few other problems you are likely to eventually run into:
Header values are supposed to be encoded if they contain non-ASCII text (see rfc2047 and rfc2231 for details).
Some header values in the wild are not properly encoded, and sometimes, even though they are not supposed to, include undeclared 8-bit text. Dealing with this is non-trivial. This also means that you cannot really use a StreamReader to read lines as you'll lose the original byte sequences.
If you actually want to do anything with the body of the message, you'll have to write a MIME parser.
I'd highly recommend using MimeKit and my other library, MailKit, for POP3 support.
Trust me, you are in for a world of pain trying to do this the way you are trying to do it.
String.Split is not powerful enough for this task. You wiil have to use Regex. The pattern that I suggest is:
^(?<name>\w+): (?<value>.*?)$
The meaning is:
^ Beginning of line (if you use the multiline option).
(?<name>pattern) Capturing group where the group name is "name".
\w+ A word.
.*? Any sequence of characters (for the value)
$ End of line
This code ...
MatchCollection matches =
Regex.Matches(text, #"^(?<name>\w+): (?<value>.*?)$", RegexOptions.Multiline);
foreach (Match match in matches) {
Console.WriteLine("{0} = {1}",
match.Groups["name"].Value,
match.Groups["value"].Value
);
}
... produces this output:
Received = from TMD-I31S3H51L29 (host-static-46-55-3-85.m ...
From = mail_address#gmail.com
To = mail_address#gmail.com
Date = Wed, 16 Apr 2014 13:48:21 -0700 (PDT)
Subject = Test message
The body seems to be start after the "Content-Transfer-Encoding:" line and goes to the end of the string. You can find the body like this:
Match body =
Regex.Match(text, #"^Content-Transfer-Encoding: .*?$", RegexOptions.Multiline);
if (body.Success) {
Console.WriteLine(text.Substring(body.Index + body.Length + 1));
}
In case the lines are separated by LineFeeds only the RegexOptions.Multiline might not works. Then you would have to replace the beginning and end of line symbols (^ and $) by \n in the regex expressions.

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