I'm trying to make a transport agent that parses the body of an email to find the pertinent pieces of information and replaces the generic subject line with specific details. My problem is that a subject line that should read like:
ABC Co Error: No status reason code (0123456)
instead shows up as
A B C C o E r r o r : N o s t a t u s r e a s o n c o d e ( 0 1 2 3 4 5 6 )
The email is plain text and encoded in us-ascii according to the email header. My problem is that It is my understanding from this question and this question that C# uses UTF-16 as the default string encoding. The spaces between each character lead me to believe that my code is somehow implicitly converting the ASCII to UTF-16, but I don't know where this would be happening. Any ideas on how to make this work properly?
void OnSubmittedMessageHandler(SubmittedMessageEventSource source, QueuedMessageEventArgs args)
{
this.mailItem = args.MailItem;
for (int intCounter = this.mailItem.Recipients.Count - 1; intCounter >= 0; intCounter--)
{
// Check if the email was sent to automated@mydomain.com
string msgRecipientP1 = this.mailItem.Recipients[intCounter].Address.LocalPart;
if (msgRecipientP1.ToLower() == "automated")
{
// Read the body of the email
string line = "";
Dictionary<string, string> EDIErrors = new Dictionary<string, string>();
Body body = this.mailItem.Message.Body;
Stream originalBodyContent = body.GetContentReadStream();
StreamReader streamReader = new StreamReader(originalBodyContent, System.Text.Encoding.ASCII, true);
while ((line = streamReader.ReadLine()) != null)
{
if (line.IndexOf("Partner:") > 0)
{
line.Replace(": ", ":");
string[] lineParts = line.Split(new[] { " " }, StringSplitOptions.None);
foreach (string EDIErrorPart in lineParts)
{
int idx = EDIErrorPart.IndexOf(':');
int qidx = EDIErrorPart.IndexOf('"');
if (idx > 0)
{
EDIErrors[EDIErrorPart.Substring(0, idx).ToLower()] = EDIErrorPart.Substring(idx + 1).ToLower();
}
else if (qidx > 0)
{
EDIErrors["Message"] = EDIErrorPart.Replace("\"", string.Empty);
}
}
}
}
if (originalBodyContent != null)
{
originalBodyContent.Close();
}
// Build the new Subject line and the recipient groups
string sOrder;
string sMessage;
string sDistroGroup;
EDIErrors.TryGetValue("Order", out sOrder);
EDIErrors.TryGetValue("Message", out sMessage);
EDIErrors.TryGetValue("Partner", out sDistroGroup);
string NewSubject = sPartner + " Error: " + sMessage + "(" + sOrder + ")";
this.mailItem.Message.Subject = NewSubject;
if (IsTicketable)
{
this.mailItem.Recipients.Add(new RoutingAddress("helpdesk@mydomain.com"));
}
}
}
return;
}