Sunday, April 30, 2006

MHTML, AOL, C#, and the new WebBrowser

Recently, I had a customer who used AOL as their primary email account. This was a CEO so it was important to accomodate their desired email vendor. Well, AOL doesn't support MIME HTML (MHTML). Since the data being reporting was coming out of SQL Server Reporting Services, the choices for output were limited. The CEO liked the layout of the MHTML, but there was a hex dump at the end of the emails. He wanted to keep the look of the emails but without the hex dump.

The solution to this problem, and I hope this helps someone else, was to write a custom C# program to rip out the meta tags in the emails. There were several tricks that needed to be applied so I will list them here for someone else.

1. Switch the program.cs code to instantiate a form but don't run it directly. Make the application run a null value. This keeps the form from popping:

static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Main main = new Main(args);
Application.Run();
}

2. Use the new webbrowser control in .NET 2.0. You can then grab the DocumentText from the browser control AFTER it finishes rendering:

class Main
{
string report;
string reportName;
string distributionList;
static string server = "mail.savian.net";
WebBrowser browser = new WebBrowser();

public Main(string[] args)
{
if (args.Length < 2)
MessageBox.Show("Too few arguments to process");
else
{
distributionList = args[1];
ConvertReportToHtml(args[0]);
reportName = args[0].Substring(args[0].LastIndexOf('\\') + 1).Replace(".mhtml", "");
}
}

private void ConvertReportToHtml(string p)
{
browser.Navigate(p);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
}

void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
report = browser.DocumentText;
StripMhtmlSection();
SendReport();
}

private void StripMhtmlSection()
{
Regex regex = new Regex(@"");
regex.Replace(report, "");
}

private void SendReport()
{
try
{
SmtpClient client = new SmtpClient(server);
MailAddress from = new MailAddress("CCLeadManagementSystem@savian.net");
MailAddress to = new MailAddress(distributionList);
MailMessage message = new MailMessage(from, to);
message.IsBodyHtml = true;
message.Subject = reportName;
message.Body = report;
client.Send(message);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Application.Exit();
}
}


I hope this helps someone. It took a lot of time to figure this all out. I tried FileWebRequest as well to no avail.


Alan

SAS throwing RPC error

If you are doing code in C#  and get this error when creating a LanguageService: The RPC server is unavailable. (Exception from HRESULT:...