Skip to main content

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;


}
}

Popular posts from this blog

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Gr...

Sending a Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post  I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API  which requires using OAuth authentication to get an Access Token. The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library  https://github.com/bblanchon/ArduinoJson  which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater. To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually  with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You ...

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why ...
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.