Friday, October 26, 2007

Uploading a document into a SharePoint Document library from a Exchange 2007 Transport Agent.

SharePoint servers these days are multiplying like rabbits while Sharepoint is a great place to put and index information breaking habits and making sure you have a central repository of things is always a challenge. What this agent does is looks at any email which has any Pdf attachments that have the word “quote” in the filename if these emails have any external recipients this document will get uploaded into a specific SharePoint’s sites shared documents library. So this allows me in this case to have a central repository of all the quotes sent out via email. To make sure the documents that are being uploaded have a unique filename the processing time is added to the filename of the document at the time it’s uploaded to SharePoint.

Because programmatically uploading a document into SharePoint isn’t that straight forward To upload the document into the SharePoint Document library itself I’ve use the S.S. Ahmed cool WSUploadservice which is free,easy to install and use you can get the source from codeplex http://www.codeplex.com/wsuploadservice.

Stepping through the code

The first part of this code is responsible for doing the recipient check as I was only interested in capturing email that was going to be delivered to a external recipient I need some code that would first check the recipient list.

ArrayList dmarray = new ArrayList();
dmarray.Add("domain.com");
Boolean pmProcMessage = false;
EmailMessage emMessage = e.MailItem.Message;
foreach (EnvelopeRecipient recp in e.MailItem.Recipients) {
if (dmarray.Contains(recp.Address.DomainPart)== false) {
pmProcMessage = true;
}

}

This code loops though the recipients of the message and checks the domainpart of the recipient address to see if it matches any of the internal domains. I could have quiered active directory to get the internal domain address information but for performance reasons Its probably better to either hardcode them in the code or put them in a registry key.

The next section of code processes any attachments on a message that is identiified as having a external recipeint. The following line will find any attachments that have a pdf attachment with quote in the filename

if (feFileExtension.ToLower() == ".pdf" | atAttach.FileName.ToLower().IndexOf("quote") != -1)

The next section of code is what performs the Sharepoint upload using the WSUploadservice service. Because Transport agents run under the \NetworkService account privileges to be able to successfully upload a document to a SharePoint site alternate credentials or impersonation must be used. I took the easy way out by using hard coded credentials in the code itself.

string spDocumentLibrary = "http://server/sites/Quotes/Shared%20Documents";
string strUserName = "username";
string strPassword = "password";
string strDomain = "domain";
System.Net.CredentialCache spUploadUserCredentials = new System.Net.CredentialCache();
spUploadUserCredentials.Add(new System.Uri(spDocumentLibrary),
"NTLM", new System.Net.NetworkCredential(strUserName, strPassword, strDomain) ); spUploader.PreAuthenticate = true;
spUploader.Credentials = spUploadUserCredentials;
urUploadResult = spUploader.UploadDocument(fnFileName.ToLower().Replace(".pdf", nfNewFileName), atBytes, spDocumentLibrary);
return urUploadResult;

To use this code you first need to have the WSuploadservice installed on your target SharePoint server. You then need to configure the URL of the SharePoint document library you want to use as well as the user account detail for the account that is going to upload the document to SharePoint and also set your local email domains in the code.

I would consider what this code is doing is pretty heavy lifting so before doing this type of thing in production you might want to ask yourself will it scale?. Its something you can really only determine yourself though your own testing based on the size and volume of information you’re going to process.

I’ve put a download of this code here the full agent looks like

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using Microsoft.Exchange.Data.Transport;
using Microsoft.Exchange.Data.Mime;
using Microsoft.Exchange.Data.Transport.Email;
using Microsoft.Exchange.Data.Transport.Smtp;
using Microsoft.Exchange.Data.Transport.Routing;
using Microsoft.Exchange.Data.Common;
using SharepointAttachmentUploadAgent.UploadwebService;

namespace msgdevExchangeRoutingAgents
{
public class SharepointAttachmentUploadFactory : RoutingAgentFactory
{
public override RoutingAgent CreateAgent(SmtpServer server)
{
RoutingAgent emSpUpload = new SharepointAttachUploadAgent();
return emSpUpload;
}
}
}
public class SharepointAttachUploadAgent : RoutingAgent
{
public SharepointAttachUploadAgent()
{
base.OnSubmittedMessage += new SubmittedMessageEventHandler(SharepointAttachUploadAgent_OnSubmittedMessage);
}

void SharepointAttachUploadAgent_OnSubmittedMessage(SubmittedMessageEventSource source, QueuedMessageEventArgs e)
{
ArrayList dmarray = new ArrayList();
dmarray.Add("domain.com");
Boolean pmProcMessage = false;
EmailMessage emMessage = e.MailItem.Message;
foreach (EnvelopeRecipient recp in e.MailItem.Recipients) {
if (dmarray.Contains(recp.Address.DomainPart)== false) {
pmProcMessage = true;
}

}
if (pmProcMessage == true) { ProcessMessage(emMessage); }
}
public static byte[] ReadFully(Stream stream, int initialLength)
{
// ref Function from http://www.yoda.arachsys.com/csharp/readbinary.html
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < initiallength =" 32768;" buffer =" new" read =" 0;" chunk =" stream.Read(buffer,"> 0)
{
read += chunk;

// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();

// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}

// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
static void ProcessMessage(EmailMessage emEmailMessage)
{
for (int index = emEmailMessage.Attachments.Count - 1; index >= 0; index--)
{
Attachment atAttach = emEmailMessage.Attachments[index];
if (atAttach.EmbeddedMessage == null)
{
if (atAttach.AttachmentType == AttachmentType.Regular & atAttach.FileName != null)
{
// Find Any PDF attachments with Quote in the File Name
if (atAttach.FileName.Length >= 3)
{
String feFileExtension = atAttach.FileName.Substring((atAttach.FileName.Length - 4), 4);
if (feFileExtension.ToLower() == ".pdf" | atAttach.FileName.ToLower().IndexOf("quote") != -1)
{
Stream attachstream = atAttach.GetContentReadStream();
String uploadResult = uploadAttachment(attachstream, atAttach.FileName.ToString());
}

}
}
atAttach = null;
}
}
}
static string uploadAttachment(Stream atAttachStream,String fnFileName) {
string nfNewFileName = "-Sent(" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")+").pdf";

string urUploadResult;
byte[] atBytes = ReadFully(atAttachStream, (int)atAttachStream.Length);
Files spUploader = new Files();
string spDocumentLibrary = "http://servername/sites/Quotes/Shared%20Documents";
string strUserName = "username";
string strPassword = "password";
string strDomain = "domain";
System.Net.CredentialCache spUploadUserCredentials = new System.Net.CredentialCache();
spUploadUserCredentials.Add(new System.Uri(spDocumentLibrary),
"NTLM",
new System.Net.NetworkCredential(strUserName, strPassword, strDomain)
);
spUploader.PreAuthenticate = true;
spUploader.Credentials = spUploadUserCredentials;
urUploadResult = spUploader.UploadDocument(fnFileName.ToLower().Replace(".pdf", nfNewFileName), atBytes, spDocumentLibrary);
return urUploadResult;


}
}

Thursday, October 18, 2007

Exchange 2007 Content Agent Log Message Tracker Gui

One of the cool features from a logging perspective on Exchange 2007 is the ability to log the SCL of every message when you have the Content Filtering Agent enabled (and also logging enabled). There is a Exchange Management Shell powershell cmdlet for reading these logs called get-agentlog which gives a good cmdline experience but as these logs are something you might want to check on a regular basis and the information contained in them is a little unwieldy to display in a cmdline environment I decided to put together a little GUI to make my life a little easier. I based the GUI on my Exchange 2000/3 WMI message tracker and I was able to carry over a lot of the cool little aggregation functions of this utility using most of the same code with a few tweaks here and there.
What this script does is creates a Winform and adds a whole bunch of controls to that winform such as datapickers, textboxes, checkboxes,labels and buttons. Its then wires ups some functions to the button clicks so that when you click the search button in will run the get-agentlog cmdlet with parameters for the daterange you specified in the GUI. To make sure you only get the events in the log that relate to the content filter it use a filter $_.agent -eq "Content Filter Agent”
The data returned by get-agent log is then added to a ADO.NET data table which is then data bound to a datagridview to display back in the form. Clicking the export button will fire a save-file dialogue box and some code will then export the table results to a csv file.
There are textboxes to allows you to search based on the from and/or To address.
There is a drop down list to allow you to select a SCL level to look at so you can choose to filter by only messages that have been assigned a specific SCL value.
The Extra sections has the aggregate options currently it has four aggregate option is can aggregate
By SCL this shows you by SCL Value how many messages where received between the dates specified
By Receiver will show you grouped by receiver how many messages have been received for each SCL value
By Sender will show you grouped by Sender(P1) how many messages have been received for each SCL value
By Date will show you by Date how many messages have been received for each SCL value.
Currently the script is only designed to be run locally on the Exchange box where the agent logs files are located. The Get-agentlog cmdlet doesn’t have a server parameter although it does have a log file location parameter so this maybe an option if you did want to run this script from a machine other then the Local Exchange server. To run the script is basically straight forward when you run it the script will build the winform and should then present this as an active window. Select the date you want to scan and the click the search button.
This is really only kind of scratching the surface of what you could do with the agent logs im working on a geolcation version so I can show the country origins of SCL values and also a version that will integrated the message tracking logs so I can include subject information in with the SCL. Also there is a lot more then just the content filtering information stored in the agent logs other things such as RBL use and effectiveness can be reported and other Transport agents that log to these files.
I’ve put a download of the code here It’s a bit to large to past verbaitem in the blog the main get-aglog section looks like
$filter = "$_.agent -eq ""Content Filter Agent"""
$dtQueryDT = New-Object System.DateTime $dpTimeFrom.value.year,$dpTimeFrom.value.month,$dpTimeFrom.value.day,$dpTimeFrom2.value.hour,$dpTimeFrom2.value.minute,$dpTimeFrom2.value.second
$dtQueryDTf = New-Object System.DateTime $dpTimeFrom1.value.year,$dpTimeFrom1.value.month,$dpTimeFrom1.value.day,$dpTimeFrom3.value.hour,$dpTimeFrom3.value.minute,$dpTimeFrom3.value.second
if ($extrasettings -eq 0){
get-agentlog -StartDate $dtQueryDT -EndDate $dtQueryDTf | where {$filter} | ForEach-Object {
$exclude = 0
if ($sclFilterboxCheck.Checked -eq $true -band $_.ReasonData -ne $sclFilterboxDrop.SelectedItem){$exclude = 1}
$repstring = ""
$incRec = $false
$p2string = [string]::join(" , ", $_.P2FromAddresses)
$repstring = [string]::join(" , ",$_.Recipients)
if ($snSenderAddressTextBox.text -ne ""){
if ($snSenderAddressTextBox.text.ToString().ToLower() -eq $_.P1FromAddress.ToString().ToLower()){
$incRec = $true
}
}
else {
if ($snRecipientAddressTextBox.text.ToString().ToLower() -ne ""){
if ($repstring -match $snRecipientAddressTextBox.text.ToString().ToLower()){
$incRec = $true
}
}
else{$incRec = $true}
}
if ($incRec -eq $true -band $exclude -eq 0){$ssTable.Rows.Add($_.Timestamp,$_.P1FromAddress,$p2string,$repstring,$_.Action,$_.Reason,$_.ReasonData)}
}
$dgDataGrid.DataSource = $ssTable}
else{
get-agentlog -StartDate $dtQueryDT -EndDate $dtQueryDTf | where {$filter} | ForEach-Object {
if ($GroupbySCL.Checked -eq $true){
[String]$sclival = "SCL " + $_.ReasonData
if ($sclhash.ContainsKey($sclival)){
$tsize = [int]$sclhash[$sclival] + 1
$sclhash[$sclival] = $tsize
}
else{
$sclhash.add($sclival,1)
}

}
if ($GroupByReciever.Checked -eq $true){
foreach($recp in $_.Recipients){
$sclagkey = $recp.ToString().replace("|","-") + "|" + $_.ReasonData
AggResults($sclagkey)
}

}
if ($GroupBySender.Checked -eq $true){
$sclagkey = $_.P1FromAddress.ToString().replace("|","-") + "|" + $_.ReasonData
AggResults($sclagkey)
}
if ($GroupByDate.Checked -eq $true){
$sclagkey = $_.Timestamp.toshortdatestring().replace("|","-") + "|" + $_.ReasonData
AggResults($sclagkey)
}

}

foreach($sclval in $sclhash.keys){
$sclTable.rows.add("",$sclval,$sclhash[$sclval])
}
foreach($adr in $gbhash1.keys){
$daDatarray = $adr.split("|")
$sclTable.rows.add($daDatarray[0],$daDatarray[1],$gbhash1[$adr])
}
$dgDataGrid.DataSource = $sclTable


}
}

Wednesday, October 17, 2007

Adding an attachment in a Transport Agent on Exchange 2007

This is a quick post to give an example of something that from the outset I would have thought would be easy but for some reason took me a little time to get my head around. Having been using CDOSYS/EX for a number of years adding a attachment to a message Is as easy as just using the addattachment method and specifying the filepath and the class will do the rest and add that attachment to the message. When working in a transport agent with the Microsoft.Exchange.Data.Transport.Email class to add an attachment you can use the attachment collections add method. There is an overload for this method that allows you to specify the filename which I thought would mean that this would work like CDOSYS’s addattachment method which didn’t turn out to be the case. Using this overload just gives you a blank attachment object with the filename property set. So to add an attachment within a Transport agent you first need to open the file in question and read-in the stream of bytes from the file and then write that stream into the attachment objects stream and then make sure you flush the attachment stream to have it committed to the message.

The following is a partial code sample of adding a word document as an attachment to a message in a Transport Agent.

void EmailAddAttachmentAgent_OnSubmittedMessage(SubmittedMessageEventSource source, QueuedMessageEventArgs e)
{

Attachment newattach = e.MailItem.Message.Attachments.Add("answer.doc");
Stream fsFileStream1 = new FileStream(@"C:\temp\answer.doc", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] bytes1 = ReadFully(fsFileStream1, (int)fsFileStream1.Length);
Stream newattachstream = newattach.GetContentWriteStream();
newattachstream.Write(bytes1, 0, bytes1.Length);
newattachstream.Flush();
newattachstream.Close();

}

public static byte[] ReadFully(Stream stream, int initialLength)

{

// ref Function from http://www.yoda.arachsys.com/csharp/readbinary.html
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)

{
read += chunk;

// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{

int nextByte = stream.ReadByte();
// End of stream? If so, we're done
if (nextByte == -1)

{
return buffer;
}

// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;

}

}

// Buffer is now too big. Shrink it.

byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;

}

Thursday, October 04, 2007

Adding Document Favorite links for Direct File Access in OWA 2007 via a script

Direct File access is a pretty cool feature of OWA 2007 although may not be the easiest thing for your average user to get their head around. Somebody asked a question about pre-populating the favorites for a user which is a pretty good idea (actually when you think about it you really want something that’s policy driven). Currently there is no really easy or supported way of doing this programmatically. The document links themselves are stored in a storage item with a messageclass of IPM.Configuration.Owa.DocumentLibraryFavorites in the associated folder collection of NON_IPM_Subtree root of a mailbox. On this storage item there is a binary mapi property 0x7C080102 and the links are stored in a XML document.

I decided to see if I could write a script that could open this storage item and then add some nodes into the already existing property or create the property if it didn’t exist. The format of the doclib node looks something like

<docLib uri="file://sername/directory" dn="DisplayName"
hn="servername" uf="2"/>

This isn’t documented anywhere so I can only hazard to guess at that these elements actually mean but logically I would think

Uri - Path to the directory or sharepoint server

Dn – The displayName in OWA

Hn – HostName ?

Uf – This property seems to get set to one of 3 values which affects the way the icon shows in OWA if you have added just a hostname then it gets set to 2, if you add a share mapping it gets set to 6 if you added a deep url mapping eg a couple of directorys deep it gets set to 34.

From what I’ve noticed the IPM.Configuration.Owa.DocumentLibraryFavorites storage item only gets created the first time the user click on the documents link in OWA so the item wouldn’t be there normally if the user has not logged onto OWA or has never clicked this link.

As I said this script is unsupported and pretty untested and should only be used in test/dev environment. Also make sure you know how to use a Mapi editor like Outlook Spy or mfcMapi worse case is you’ll stuff up the IPM.Configuration.Owa.DocumentLibraryFavorites object and need to delete it.

The script uses CDO 1.2 to use the script you need to configure the first 4 lines which reflect the doclib I just talked about,

shareDN = "temp"
ShareHostName = "servername"
Shareuf = "6"
ShareURI = "file://servername/temp"

and then the 6,7 with the servername and mailboxname of the mailbox you want to access.

I’ve put a download of the script here the code itself look like

shareDN = "temp"
ShareHostName = "servername"
Shareuf = "6"
ShareURI = "file://servername/temp"

snServername = "mailserver"
mbMailboxName = "mailbox"

Const PR_PARENT_ENTRYID = &H0E090102
set xdXmlDocument = CreateObject("Microsoft.XMLDOM")
xdXmlDocument.async="false"
ifound = false
Set objSession = CreateObject("MAPI.Session")
objSession.Logon "","",false,true,true,true,snServername & vbLF & mbMailboxName
Set CdoInfoStore = objSession.GetInfoStore
Set CdoFolderRoot = CdoInfoStore.RootFolder
set non_ipm_rootfolder =
objSession.getfolder(CdoFolderRoot.fields.item(PR_PARENT_ENTRYID),CdoInfoStore.id)
For Each soStorageItem in non_ipm_rootfolder.HiddenMessages
If soStorageItem.Type = "IPM.Configuration.Owa.DocumentLibraryFavorites" Then
ifound = true
Set actionItem = soStorageItem
End if
Next
If ifound = false Then
wscript.echo "No Storage Item Found"
Else
On Error Resume Next
hexString = actionItem.fields(&h7C080102).Value
If Err.number <> 0 Then
On Error goto 0
wscript.echo "Property not set"
actionItem.fields.Add &h7C080102, vbBlob
actionItem.fields(&h7C080102).Value = StrToHexStr("<docLibs></docLibs>")
actionItem.update
hexString = actionItem.fields(&h7C080102).Value
End If
On Error goto 0
wscript.echo hextotext(hexString)
xdXmlDocument.loadxml(hextotext(hexString))
Set xnNodes = xdXmlDocument.selectNodes("//docLibs")
update = false
Call Adddoclib(shareDN,ShareHostName,Shareuf,ShareURI,xnNodes)
If update = True Then
nval = StrToHexStr(CStr(xdXmlDocument.xml))
actionItem.fields(&h7C080102).Value = nval
actionItem.update
wscript.echo "Storage Object Updated"
Else
wscript.echo "No Updates Performed"
End If
End If



Function hextotext(binprop)
arrnum = len(binprop)/2
redim aout(arrnum)
slen = 1
for i = 1 to arrnum
if CLng("&H" & mid(binprop,slen,2)) <> 0 then
aOut(i) = chr(CLng("&H" & mid(binprop,slen,2)))
end if
slen = slen+2
next
hextotext = join(aOUt,"")
end Function

Function StrToHexStr(strText)
Dim i, strTemp
For i = 1 To Len(strText)
strTemp = strTemp & Right("0" & Hex(Asc(Mid(strText, i, 1))), 2)
Next
StrToHexStr = Trim(strTemp)
End Function

Function Searchfordoclib(elElementName,cnvalue,XMLDoc)
Set xnSearchNodes = XMLDoc.selectNodes("//*[@" & elElementName & " = '" &
cnvalue & "']")
If xnSearchNodes.length = 0 Then
Searchfordoclib = False
else
Searchfordoclib = True
End if

End Function

sub Adddoclib(dn,hn,uf,uri,xnNodes)
If Searchfordoclib("dn",dn,xdXmlDocument) = False then
Set objnewEle = xdXmlDocument.createElement("docLib")
objnewEle.setAttribute "uri",uri
objnewEle.setAttribute "dn",dn
objnewEle.setAttribute "hn", hn
objnewEle.setAttribute "uf", uf
xnNodes(0).appendchild objnewEle
update = true
Else
wscript.echo "Dn exists " & DN
End if
End sub

Monday, October 01, 2007

Processing embedded attachments in a Transport Agent

Continuing on from my other post last week this is a little bit more of an advanced Transport agent that can process attachments within embedded messages down to any depth. Most of the code is the same as last week except that the structure of the code has been changed so each message and embedded message is processed by the routine. To see if a attachment has an assoiciated embeeded message all you need to do is check the EmbeddedMessage property on each message. The one thing that I found interesting is when processing an embedded message vs. just processing the message that caused the Agent to fire is that there is no underlying MIME document so the code I had that was saving out the message to a separate directory using the MIME document in this case wouldn’t work for an embedded message. As I was really only interested in processing attachments this was not so much of a problem but its one thing to be careful of if you do what to processes embedded messages. For details of what this code does please read last weeks post.

I’ve put a download of the code here the code itself looks like

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using Microsoft.Exchange.Data.Transport;
using Microsoft.Exchange.Data.Mime;
using Microsoft.Exchange.Data.Transport.Email;
using Microsoft.Exchange.Data.Transport.Smtp;
using Microsoft.Exchange.Data.Transport.Routing;
using Microsoft.Exchange.Data.Common;

namespace msgdevExchangeRoutingAgents
{
public class EmailArchivingFactory : RoutingAgentFactory
{
public override RoutingAgent CreateAgent(SmtpServer server)
{
RoutingAgent emMailArchive = new EmailArchivingRoutingAgent();
return emMailArchive;
}
}
}

public class EmailArchivingRoutingAgent : RoutingAgent
{
public EmailArchivingRoutingAgent()
{
base.OnSubmittedMessage += new SubmittedMessageEventHandler(EmailArchivingRoutingAgent_OnSubmittedMessage);
}

void EmailArchivingRoutingAgent_OnSubmittedMessage(SubmittedMessageEventSource source, QueuedMessageEventArgs e)
{
EmailMessage emMessage = e.MailItem.Message;
String MessageGuid = Guid.NewGuid().ToString();
ProcessMessage(emMessage, MessageGuid);

}
public static byte[] ReadFully(Stream stream, int initialLength)
{
// ref Function from http://www.yoda.arachsys.com/csharp/readbinary.html
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < initiallength =" 32768;" buffer =" new" read =" 0;" chunk =" stream.Read(buffer,"> 0)
{
read += chunk;

// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();

// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}

// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
static void ProcessMessage(EmailMessage emEmailMessage, String MessageGuid)
{
//Archive Message


if (emEmailMessage.MimeDocument != null)
{

Stream fsFileStream = new FileStream(@"C:\temp\archive\messages\" + MessageGuid + ".eml", FileMode.OpenOrCreate);
emEmailMessage.MimeDocument.WriteTo(fsFileStream);
fsFileStream.Close();
}
//Archive Any Attachments Check for pdf attachments under 20 K and delete
ArrayList adAttachmenttoDelete = new ArrayList();
for (int index = emEmailMessage.Attachments.Count - 1; index >= 0; index--)
{
Attachment atAttach = emEmailMessage.Attachments[index];
if (atAttach.EmbeddedMessage != null)
{
EmailMessage ebmMessage = atAttach.EmbeddedMessage;
ProcessMessage(ebmMessage, MessageGuid);
}
else
{
if (atAttach.AttachmentType == AttachmentType.Regular & atAttach.FileName != null)
{
FileStream atFileStream = File.Create(Path.Combine(@"C:\temp\archive\attachments\", MessageGuid + "-" + atAttach.FileName));
Stream attachstream = atAttach.GetContentReadStream();
byte[] bytes = ReadFully(attachstream, (int)attachstream.Length);
atFileStream.Write(bytes, 0, bytes.Length);
atFileStream.Close();
atFileStream = null;
bytes = null;
// Find Any PDF attachments less then 20 KB
if (atAttach.FileName.Length >= 3)
{
String feFileExtension = atAttach.FileName.Substring((atAttach.FileName.Length - 4), 4);
if (feFileExtension.ToLower() == ".pdf" & attachstream.Length < 20480)
{
adAttachmenttoDelete.Add(atAttach);
}

}
attachstream.Close();
attachstream = null;
}
atAttach = null;
}
}
//Delete Attachments
if (adAttachmenttoDelete.Count != 0)
{
IEnumerator Enumerator = adAttachmenttoDelete.GetEnumerator();
while (Enumerator.MoveNext())
{
emEmailMessage.Attachments.Remove((Attachment)Enumerator.Current);
}
}

}
}