Access & Read Email Messages from MS SharePoint Document Library
-
This technical tip shows how to read email messages from Microsoft SharePoint document library. For accessing the files from SharePoint document library, SharePoint SDK must be installed on the system, which provides the necessary API for logging in and accessing files from the document library. In the below code snippet, we will assume that an Outlook Message file (.msg) is already stored in the SharedDocument folder of SharePoint Document Library. We will utilize SharePoint SDK to get the message file in a stream and pass this stream to an instance of Aspose.Email's MailMessage class. MailMessage class will load the stream and parse the Outlook Message file. After that you can easily access the properties of MailMessage class e.g. Subject , TextBody , HtmlBody| etc and utilize that information in your Visual Studio project.
[C#]
// private members
private SPSite site = null;
private SPWeb web = null;/// <summary>
/// This Method is called throug Delegate elevatedGetSite which is definend in button2_Click
/// </summary>
private void EstablishSharepoint()
{
site = new SPSite("http://localhost/Site1");
web = site.OpenWeb();
}/// <summary>
/// click event of a windows form button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
SPSecurity.CodeToRunElevated elevatedGetSite = new SPSecurity.CodeToRunElevated(EstablishSharepoint);
SPSecurity.RunWithElevatedPrivileges(elevatedGetSite);// path to the msg file stored in Shared Documents folder
SPFile msgFile = web.GetFile("Shared Documents/Test.msg");// Read the file into a Memory Stream.
MemoryStream fileStream = new MemoryStream();
byte[] currentFileContent = msgFile.OpenBinary();
fileStream.Write(currentFileContent, 0, currentFileContent.Length);
fileStream.Position = 0;// Create an instance of MailMessage class
// and pass the memory stream of .msg file to it
MailMessage msg = MailMessage.Load(fileStream, MessageFormat.Msg);
fileStream.Close();
fileStream.Dispose();// access public properties of MailMessage class