VS.NET 2010 (and above) Users Click Here   

HOMECONTACT PRODUCTS DOWNLOADS PURCHASE TESTIMONIALS FORUMS COMPANY CONTACT
Home
Products
Downloads
Purchase
Licensing
Licensing FAQ
Software Updates
Support Forums
Testimonials
Feature Requests
Guarantee
About Us
Contact Us
Hosting Companies
Privacy Policy
   
Shopping Cart


Search

aspNetIMAP: Fetching Headers, Size, Importance and Flags

by Dave 8. March 2011 00:58

I recently had a request about fetching different parts of a message from an IMAP server.  They wanted to get the following information as easily as possible:

Flags
Message Size
Importance
Attachment Names
Customer Headers
Recipients

The IMAP protocol does not support fetching this information in a single network call. However, all of these values can be fetched for a single message, using multiple calls. aspNetIMAP can do this for you in a nice, neat object called the MimeEnvelope object.  The MimeEnvelope object fetches all of the above data, and more.

Below is a code example that demonstrates using the MimeEnvelope object.

C#

	 IMAP4 imap = new IMAP4();
	 imap.Server = "192.168.1.4";
	 imap.Username = "dave@example.com";
	 imap.Password = "test";
	 imap.Login();
	 
	 MailFolder mf = imap.SelectInbox();       
	 
	 FetchClient fc = mf.FetchClient;
	 
	 MimeEnvelope[] menvelopes = fc.MimeEnvelope( "1:*", IndexType.Ordinal );
	 
	 
	 foreach( MimeEnvelope menvelope in menvelopes)
	 {
	 	//write out the attachment names
	 	Response.Write( "Attachment Count: " + menvelope.AttachmentNames.Length );
	 	if( menvelope.AttachmentNames.Length > 0 )
	 	{
	 		foreach( string attachmentName in menvelope.AttachmentNames )
	 		{
	 			Response.Write( attachmentName );
	 		}
	 	}
	 
	 	//write out the From, To, CC address information
	 	Response.Write( menvelope.FromName );
	 	Response.Write( menvelope.FromAddress );
	 	//To addresses
	 	foreach( string emailAddress in menvelope.To )
	 	{
	 		string name = menvelope.To[ emailAddress ];
	 		Response.Write( name );
	 		Response.Write( emailAddress );
	 	}
	 	//CC Addresses
	 	foreach( string emailAddress in menvelope.CC )
	 	{
	 		string name = menvelope.CC[ emailAddress ];
	 		Response.Write( name );
	 		Response.Write( emailAddress );
	 
	 	}
	 
	 	//write out other information
	 	Response.Write( "UniqueId: " + menvelope.UniqueId.ToString() );
	 	Response.Write( "Size: " + menvelope.Size.ToString() );
	 	Response.Write( "Flags: "+ menvelope.Flags.ToString() );
	 	Response.Write( "InternalDate: " + menvelope.InternalDate.ToString( "f",  DateTimeFormatInfo.InvariantInfo) );
	 	Response.Write( "Date: " + menvelope.Date.ToString( "f",  DateTimeFormatInfo.InvariantInfo) );
	 
	 	//subject
	 	Response.Write( menvelope.Subject );
	 	
	 	//priority
	 	Response.Write( "Priority: " + menvelope.Priority.ToString() );
	 
	 	Response.Write( "IsAnswered: " + menvelope.IsAnswered().ToString() );
	 	Response.Write( "IsDrafted: " + menvelope.IsDrafted().ToString() );
	 	Response.Write( "IsFlagged: " + menvelope.IsFlagged().ToString() );
	 	Response.Write( "IsRead: " + menvelope.IsRead().ToString() );
	 	Response.Write( "IsRecent: " + menvelope.IsRecent	().ToString() );
	 
	 	//retrieve a specific header named 'x-organization'
	 	Header h = menvelope.Headers[ "x-organization" ];
	 	if( ( h != null ) && ( h.Value != null ) )
	 	{
	 		Response.Write( h.Value );
	 	}
	 
	 	//write out the headers
	 	Response.Write( menvelope.HeaderString );
	 
	 	//write out the bodystructure of the message
	 	if( menvelope.BodyStructure != null )
	 	{
	 		Response.Write( menvelope.BodyStructure.ToString() );
	 	}
	 }
	 
	 
	 imap.Disconnect();
	 

VB.NET

	 Dim imap As New IMAP4()
	 imap.Server = "192.168.1.4"
	 imap.Username = "dave@example.com"
	 imap.Password = "test"
	 imap.Login()
	 
	 Dim mf As MailFolder = imap.SelectInbox()
	 
	 Dim fc As FetchClient = mf.FetchClient
	 
	 Dim menvelopes As MimeEnvelope() = fc.MimeEnvelope("1:*", IndexType.Ordinal)
	 
	 
	 Dim menvelope As MimeEnvelope
	 For Each menvelope In  menvelopes
	    'write out the attachment names
	    Response.Write(("Attachment Count: " + menvelope.AttachmentNames.Length))
	    If menvelope.AttachmentNames.Length > 0 Then
	       Dim attachmentName As String
	       For Each attachmentName In  menvelope.AttachmentNames
	          Response.Write(attachmentName)
	       Next attachmentName
	    End If
	    
	    'write out the From, To, CC address information
	    Response.Write(menvelope.FromName)
	    Response.Write(menvelope.FromAddress)
	    'To addresses
	    Dim emailAddress As String
	    For Each emailAddress In  menvelope.To
	       Dim name As String = menvelope.To(emailAddress)
	       Response.Write(name)
	       Response.Write(emailAddress)
	    Next emailAddress
	    'CC Addresses
	    Dim emailAddress As String
	    For Each emailAddress In  menvelope.CC
	       Dim name As String = menvelope.CC(emailAddress)
	       Response.Write(name)
	       Response.Write(emailAddress)
	    Next emailAddress 
	    
	    'write out other information
	    Response.Write(("UniqueId: " + menvelope.UniqueId.ToString()))
	    Response.Write(("Size: " + menvelope.Size.ToString()))
	    Response.Write(("Flags: " + menvelope.Flags.ToString()))
	    Response.Write(("InternalDate: " + menvelope.InternalDate.ToString("f", DateTimeFormatInfo.InvariantInfo)))
	    Response.Write(("Date: " + menvelope.Date.ToString("f", DateTimeFormatInfo.InvariantInfo)))
	    
	    'subject
	    Response.Write(menvelope.Subject)
	    
	    'priority
	    Response.Write(("Priority: " + menvelope.Priority.ToString()))
	    
	    Response.Write(("IsAnswered: " + menvelope.IsAnswered().ToString()))
	    Response.Write(("IsDrafted: " + menvelope.IsDrafted().ToString()))
	    Response.Write(("IsFlagged: " + menvelope.IsFlagged().ToString()))
	    Response.Write(("IsRead: " + menvelope.IsRead().ToString()))
	    Response.Write(("IsRecent: " + menvelope.IsRecent().ToString()))
	    
	    'retrieve a specific header named 'x-organization'
	    Dim h As Header = menvelope.Headers("x-organization")
	    If Not (h Is Nothing) And Not (h.Value Is Nothing) Then
	       Response.Write(h.Value)
	    End If
	    
	    'write out the headers
	    Response.Write(menvelope.HeaderString)
	    
	    'write out the bodystructure of the message
	    If Not (menvelope.BodyStructure Is Nothing) Then
	       Response.Write(menvelope.BodyStructure.ToString())
	    End If
	 Next menvelope
	 
	 
	 imap.Disconnect()

Downloading email using aspNetIMAP from Gmail

by Dave 2. March 2011 02:51


aspNetIMAP can easily fetch email from Gmail. To do this you must do the following:

a) Configure IMAP access in Gmail
b) Download the AdvancedIntellect.Ssl.dll from www.advancedintellect.com/download.aspx
c) Use aspNetIMAP over SSL at port 993 to connect.

Lets discuss this below.

Configure IMAP access in Gmail

Before you can access email, you must first configure IMAP in Gmail. To do this, log into Gmail, and click on the settings tab. You should see something similar to what is below. Basically, you want select "Enable IMAP".


Download the AdvancedIntellect.Ssl.dll
Once you have IMAP configured in Gmail, you need to download the AdvancedIntellect,Ssl.dll plugin to use with aspNetIMAP. You can download the dll from:
http://www.advancedintellect.com/download.aspx
Gmail only allows you to connect over IMAP using SSL. The  AdvancedIntellect,Ssl.dll allows you to do this.

Use aspNetIMAP over SSL at port 993 to connect.
Once you've downloaded the dll, you can integrate it into your project.

If you are using VS.NET, import the dll into your application, and set a reference to it.

If you are not using VS.NET, you should be able to just copy the dll to your /bin directory.

Once that is done, the following code example will get you started. This example simply downloads the message count from your inbox, and loops through the headers of the individual messages.


C#

IMAP4 imap = new IMAP4( "imap.gmail.com" );

//create and load the ssl socket
AdvancedIntellect.Ssl.SslSocket ssl = new AdvancedIntellect.Ssl.SslSocket();
imap.LoadSslSocket( ssl );

//logging on the ssl socket
ssl.Logging = true;
ssl.LogPath = "c:\\ssl.log";


//rest of the IMAP properties
imap.Port = 993;
imap.Username = "MyAccount@gmail.com";
imap.Password = "MyPassword";

//any logging for troubleshooting
imap.Logger = new IMAPLog();
imap.Logger.Path = "c:\\imap.log";
imap.Logger.Overwrite = true;

imap.Connect();

imap.Login();


//get the message count
MailFolder inbox = imap.SelectInbox();
int count = inbox.MessageCount;

//write it out
Response.Write( count.ToString() );

FetchClient fc = inbox.FetchClient;
//get the headers for each message (IMAP is a '1' based index. Start at '1'
for( int i=1;i<=count;i++)
{
	string headers = fc.Headers(i, IndexType.Ordinal );

	//do some work on the headers
	DoWork( headers );
}

imap.Disconnect();


VB.NET

Dim imap As New IMAP4("imap.gmail.com")

'create and load the ssl socket
Dim ssl As New AdvancedIntellect.Ssl.SslSocket()
imap.LoadSslSocket(ssl)

'logging on the ssl socket
ssl.Logging = True
ssl.LogPath = "c:\ssl.log"


'rest of the IMAP properties
imap.Port = 993

'any logging for troubleshooting
imap.Logger = New IMAPLog()
imap.Logger.Path = "c:\imap.log"
imap.Logger.Overwrite = True

imap.Connect()


imap.Username = "MyAccount@gmail.com"
imap.Password = "MyPassword"
imap.Login()


'get the message count
Dim inbox As MailFolder = imap.SelectInbox()
Dim count As Integer = inbox.MessageCount

'write it out
Response.Write(count.ToString())

Dim fc As FetchClient = inbox.FetchClient
'get the headers for each message (IMAP is a '1' based index. Start at '1'
Dim i As Integer
For i = 1 To count
   Dim headers As String = fc.Headers(i, IndexType.Ordinal)
   
   'do some work on the headers
   DoWork(headers)
Next i

imap.Disconnect()


As always, if anyone has any questions, feel free to contact me over at the Contact Us web page.


Thanks,
Dave Wanta

Fetching only Unread Messages

by Dave 17. February 2011 07:39

Today I had a request from Darren about how to read unread messages from an IMAP server. This is an excellent question. I should have added something like this to the help file.

To fetch unread messages, there are a number of classes we need to take advantage of in aspNetIMAP.

They are:
IMAP4 -- the object used to manage the connection to the IMAP server
MailFolder -- the object used to get access to the individual folder
SearchClient -- the object used to search for unread messages
FetchClient -- the object that actually fetches the content of the messages.

Without further delay, below is some sample code that can get you started for downloading unread messages.

//configure and connect to the IMAP server
IMAP4 imap = new IMAP4( "mail.blah.com", "dave@blah.com", "test" );
imap.Logger = new IMAPLog( "c:\\imap.log", false);
imap.Logger.Overwrite = true;
imap.Login();

//get the inbox
MailFolder inbox = imap.SelectInbox();

//get a list of message ids that are unread
SearchClient sc = inbox.SearchClient;

//return results as UniqueIds
sc.IndexType = IndexType.UniqueId;
string messageSet = inbox.SearchClient.NotSeenSet();

if( (messageSet == null ) || (messageSet.Length == 0 ) )
	return;

char[] commaArray = new Char[] {','};

//trim any ending commas
if( messageSet.EndsWith(",") )
	messageSet = messageSet.Trim( commaArray );

//split into individual message ids, so we can process 1 at a time.
string[] ids = messageSet.Split( commaArray);

//get an instance to the FetchClient
FetchClient fc = inbox.FetchClient;
foreach( string id in ids )
{
	if( id.Length == 0 )
		continue;

	int uid = int.Parse(id);

	//download the message
	MimeMessage msg = fc.Message( uid, IndexType.UniqueId, true );

	//process according to business rules
	ProcessMessage( msg );
}

imap.Disconnect();

To keep the code short, it is left up to the user to implement exception handling.

As always, if anyone has any questions, comments or requests, please let me know.

Thanks!
Dave Wanta

 

 

Testimonial

Works perfectly... :)I must say, this is the best customer support I have ever had. "

Ralph | idebthelp.com

Read more testimonials
ListNanny aspNetDNS aspNetEmail aspNetPOP3 aspNetMX IPMuncher aspNetMIME aspNetPING aspNetTraceRoute aspNetIMAP aspNetMHT