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)
Main main = new Main(args);

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 = "";
WebBrowser browser = new WebBrowser();

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

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

void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
report = browser.DocumentText;

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

private void SendReport()
SmtpClient client = new SmtpClient(server);
MailAddress from = new MailAddress("");
MailAddress to = new MailAddress(distributionList);
MailMessage message = new MailMessage(from, to);
message.IsBodyHtml = true;
message.Subject = reportName;
message.Body = report;
catch (Exception ex)

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


No comments:

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:...