Friday, February 13, 2009

C# Code to Read Email Attachment

I wrote code in C# to read email from POP3 server. In this case I emphasize on how to save attachment for excel and txt file. I found it is not easy to create the code. Last time I have done this with success test, but when I tried again, it failed to work. And below is my revision, any advice is welcome.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
using System.Net.Security;
using System.Text.RegularExpressions;

{
string response;
int totmessages;
string msg;
TcpClient mailclient;
SslStream NetStrm;
StreamReader sr;
StreamWriter sw;
NetworkStream ns;
string attachment;
string filename;

string[] data;
int startindex;
int index;
int lastindex;
string x;
MemoryStream ms;
FileStream fs;

//connect to POP3 server
try
{
mailclient = new TcpClient(tbPop.Text, Convert.ToInt16(tbPort.Text));
}
catch (SocketException)
{
tbMessage.Text = "Unable to connect to server 1";
return;
}

if (cbSsl.Checked)
{
NetStrm = new SslStream(mailclient.GetStream());
NetStrm.AuthenticateAsClient(tbPop.Text);
sr = new StreamReader(NetStrm);
sw = new StreamWriter(NetStrm);
}
else
{
ns = mailclient.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
}
response = sr.ReadLine(); //Get opening POP3 banner

sw.WriteLine("user " + tbUid.Text); //Send username
sw.Flush();

response = sr.ReadLine();

if (response.Substring(0, 4) == "-ERR")
{
tbMessage.Text = "Unable to log into server 2";
return;
}

sw.WriteLine("pass " + tbPwd.Text); //Send password
sw.Flush();

response = sr.ReadLine();

if (response.Substring(0, 3) == "-ER")
{
tbMessage.Text = "Unable to log into server 3";
return;
}

sw.WriteLine("stat"); //Send stat command to get number of messages
sw.Flush();

response = sr.ReadLine();

//find number of message
string[] nummess = response.Split(' ');
totmessages = Convert.ToInt16(nummess[1]);

//read emails
for (int i = 1; i <= totmessages; i++)
{
msg = null;

sw.WriteLine("top " + i + " 0"); //read header of each message
sw.Flush();
response = sr.ReadLine();

while (true)
{
response = sr.ReadLine();
if (response == ".")
break;
msg = msg + response + "\r\n";
}

//read attachment
attachment = null;
if (Regex.Match(msg, "multipart/mixed").Success)
{
msg = null;
sw.WriteLine("retr " + i.ToString()); //Retrieve entire message
sw.Flush();
response = sr.ReadLine();

while (true)
{
response = sr.ReadLine();
if (response == ".")
break;
msg = msg + response + "\r\n";
}

if (Regex.Match(msg, tbFile.Text).Success)
{

// below will not work for gmail
//sw.WriteLine("dele " + i.ToString()); //mark for deletion
//sw.Flush();

data = msg.Split('\r');

//tbMessage.Text = msg;

startindex = 0;
index = 0;
lastindex = 0;
x = null;
ms = null;
fs = null;

while (true)
{
attachment = null;
while ((!Regex.Match(data[index].Trim(), "filename").Success)&&(index {
index++;
}
if (index == data.Length-1) break;
filename = data[index].Trim().Substring(42).Replace("\"", "");

//find start of attachment data
index++;
while ((data[index].Length!=1)&&(index {
index++;
}
if (index == data.Length-1) break;
startindex = index + 1;

//find end of data
index = startindex+1;
while ((!Regex.Match(data[index].Trim(), "--0").Success) && (data[index].Length != 1) && (index < data.Length - 1))
{
index++;
}
if (index == data.Length-1) break;
lastindex = index - 1;

for (int j = startindex; j <= lastindex; j++)
{
attachment = attachment + data[j];
}
attachment = attachment + "\r\n";

//saving attachment if xls or txt
if (Regex.Match(filename.ToLower(), "xls").Success)
{
ms = new MemoryStream(Convert.FromBase64String(attachment));
fs = File.OpenWrite("D:\\" + filename);
fs.Write(ms.ToArray(), 0, ms.ToArray().Length);
fs.Close();
}
else if (Regex.Match(filename.ToLower(), "txt").Success)
{
ms = new MemoryStream(Encoding.UTF8.GetBytes(attachment));
fs = File.OpenWrite("D:\\" + filename);
fs.Write(ms.ToArray(), 0, ms.ToArray().Length);
fs.Close();
}

}
}
}
}

sw.WriteLine("quit"); //quit
sw.Flush();

}

1 comment:

Alex said...

For read mails try this tool-Excel unable to read file,program is free as far as i know,software save important information,such as graphics,statistic and mathematics,program will help you to recover valuable information and avoid its losses,tool scans your broken worksheet,then gets the data from this document,will help you to repair damaged files in Microsoft Excel sheet recognizable format,repair file Excel this file is not in a recognizable format, Excel showing this file does not in a recognizable format, or Microsoft Excel worksheet this file is not in a recognizeable format, it is an Excel file error: data may have been lost: Microsoft Excel impossible read file,tool performs a scan of your corrupt excel files not recognizable format and attempts to recover all available data.