Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Last active June 7, 2019 19:18
Show Gist options
  • Save rajeevprasanna/6b0ba1db1599500a94451958b4f52d79 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/6b0ba1db1599500a94451958b4f52d79 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Exchange.WebServices.Data;
using System.Linq;
using System.Net;
using System.Security;
using System.Text;
using System.Threading.Tasks;
// EWS API setup: https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/get-started-with-ews-managed-api-client-applications
namespace HelloWorldEws
{
class Program
{
//Office365
private static string ewsUrl = "https://outlook.office365.com/EWS/Exchange.asmx";
private static string accessToken = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjA2MDBGOUY2NzQ2MjA3MzdFNzM0MDRFMjg3QzQ1QTgxOENCN0NFQjgiLCJ4NXQiOiJCZ0Q1OW5SaUJ6Zm5OQVRpaDhSYWdZeTN6cmciLCJ0eXAiOiJKV1QifQ.eyJuYW1laWQiOiI1MDRjOTBhOC1iMzhkLTRmZTctMTIzNC1lZWQ4MTJjNTQ1YjVAMTRiYTBiYmUtYmVkNC00YWEyLWJkNzEtYTkxNjBhNzk3NDFhIiwidmVyIjoiRXhjaGFuZ2UuQ2FsbGJhY2suVjEiLCJhcHBjdHhzZW5kZXIiOiJodHRwczovLzE5Mi4xNjguNS4xMjo4MDAwL3dlYi1hZGRpbi9pbmRleC9yZWFkQDE0YmEwYmJlLWJlZDQtNGFhMi1iZDcxLWE5MTYwYTc5NzQxYSIsImFwcGN0eCI6IntcIm9pZFwiOlwiZGM2NDVhYTEtY2VhYy00ZGE1LTk0MjktYzA0YzhkNTI2OGY2XCIsXCJwdWlkXCI6XCIxMDAzMjAwMDMxOEZGNDUwXCIsXCJzbXRwXCI6XCJzYXZpdGhhQHJhZG9uNi5vbm1pY3Jvc29mdC5jb21cIixcInVwblwiOlwic2F2aXRoYU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ESL5yeE1SlFqS5Vwv5mXyI=";
private static string attachmentName = "0-neu-d3-303d630a16599a9a1070d21df143a36c.jpg";
private static int fileSize = 90355;
private static string contentType = "image/jpeg";
//exchange
//private static string ewsUrl = "https://webmail.hostingcloudapp.com/EWS/Exchange.asmx"; //exchange
//private static string accessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImthME5Hb19aNUkwRms1MXpKblZjT2tHbzFvbyJ9.eyJuYW1laWQiOiI1MDRjOTBhOC1iMzhkLTRmZTctMTIzNC1lZWQ4MTJjNTg1YjVAaG9zdGluZ2Nsb3VkYXBwLm5ldCIsInZlciI6IkV4Y2hhbmdlLkNhbGxiYWNrLlYxIiwiYXBwY3R4c2VuZGVyIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6ODAwMC93ZWItYWRkaW4vaW5kZXgvcmVhZEBob3N0aW5nY2xvdWRhcHAubmV0IiwiYXBwY3R4Ijoie1wic210cFwiOlwic3JpbmlAeGVub3Z1cy1hbWVyaWNhbmEuY29tXCIsXCJzY29wZVwiOlwiUGFyZW50SXRlbUlkOkFBTWtBREptTUdabVpUVXdMVGd6WlRjdE5EazVZeTA0WmpKbUxUWTRNell4WVRKaVltUXhNUUJHQUFBQUFBQjJtVlVQYkltUVQ3TFUrVVBwSTc2bEJ3RGhpSXdpRTFrUFNvMWcySGRjY1JvNEFBQUFBQUVNQUFEaGlJd2lFMWtQU28xZzJIZGNjUm80QUFEMjhDaGRBQUE9XCJ9IiwiaXNzIjoiMDAwMDAwMDItMDAwMC0wZmYxLWNlMDAtMDAwMDAwMDAwMDAwQGhvc3RpbmdjbG91ZGFwcC5uZXQiLCJhdWQiOiIwMDAwMDAwMi0wMDAwLTBmZjEtY2UwMC0wMDAwMDAwMDAwMDAvd2VibWFpbC5ob3N0aW5nY2xvdWRhcHAuY29tQGhvc3RpbmdjbG91ZGFwcC5uZXQiLCJleHAiOjE1NDI5NjU5MjgsIm5iZiI6MTU0Mjk2NTYyOH0.lRHqs84WGnE3lB_nJnHr2X3lQNOsm5AJrJuHhX-VK4Z3yDsnzdDI6_LAl_21gRZoQpKR97M0xDxIqxUW9e9LrUoNOcxDZ5h1inN5S0yKG7A0xL1RlYAA3ko7ghxZjDGA94WdcD_tG4a3aoXiJtDFJtGAq59y89j-Lf9y23dK_DZFriEgB-yXEM9KVd6OlMsnhm0jIG3pYH_FOTy5e8m6Blywz37TxhaJlWm8jeH_JBHD4hDPlqd42d9EX2l7JM_UdSOJuee0iNja85m4-5lIePLqeRyZ38M1ikr8d1Q54Z_uvbPgrUYeu5P-pMcvmvJcuogqAt0RXiADXImpYLOaBw";
//private static string attachmentId = "AAMkADJmMGZmZTUwLTgzZTctNDk5Yy04ZjJmLTY4MzYxYTJiYmQxMQBGAAAAAAB2mVUPbImQT7LU+UPpI76lBwDhiIwiE1kPSo1g2HdccRo4AAAAAAEMAADhiIwiE1kPSo1g2HdccRo4AAD28ChdAAABEgAQANPw47cwvjFChm/yoZEMAaM=";
//private static string attachmentName = "package.json";
//private static int fileSize = 4453;
//private static string contentType = "application/json";
static void Main(string[] args)
{
Console.WriteLine("Running program to download email attachments");
AttachmentDetails at1 = new AttachmentDetails();
at1.attachmentType = "0";
at1.contentType = contentType;
at1.id = attachmentId;
at1.name = attachmentName;
at1.isInline = false;
at1.size = fileSize;
AttachmentSampleServiceRequest attachmentSampleServiceRequest = new AttachmentSampleServiceRequest();
attachmentSampleServiceRequest.attachmentToken = accessToken;
attachmentSampleServiceRequest.ewsUrl = ewsUrl;
attachmentSampleServiceRequest.service = "attachments service";
attachmentSampleServiceRequest.attachments = new AttachmentDetails[1] { at1 };
Program instance = new Program();
AttachmentSampleServiceResponse resp = instance.GetAttachmentsFromExchangeServerUsingEWS(attachmentSampleServiceRequest);
}
public class AttachmentSampleServiceRequest
{
public string attachmentToken { get; set; }
public string ewsUrl { get; set; }
public string service { get; set; }
public AttachmentDetails[] attachments { get; set; }
}
public class AttachmentDetails
{
public string attachmentType { get; set; }
public string contentType { get; set; }
public string id { get; set; }
public bool isInline { get; set; }
public string name { get; set; }
public int size { get; set; }
}
public class AttachmentSampleServiceResponse
{
public Array attachmentNames { get; set; }
public int attachmentsProcessed { get; set; }
}
private AttachmentSampleServiceResponse GetAttachmentsFromExchangeServerUsingEWS(AttachmentSampleServiceRequest request)
{
var attachmentsProcessedCount = 0;
var attachmentNames = new List<string>();
foreach (var attachment in request.attachments)
{
// Prepare a web request object.
HttpWebRequest webRequest = WebRequest.CreateHttp(request.ewsUrl);
webRequest.Headers.Add("Authorization",
string.Format("Bearer {0}", request.attachmentToken));
webRequest.PreAuthenticate = true;
webRequest.AllowAutoRedirect = false;
webRequest.Method = "POST";
webRequest.ContentType = "text/xml; charset=utf-8";
// Construct the SOAP message for the GetAttachment operation.
byte[] bodyBytes = Encoding.UTF8.GetBytes(
string.Format(GetAttachmentSoapRequest, attachment.id));
webRequest.ContentLength = bodyBytes.Length;
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(bodyBytes, 0, bodyBytes.Length);
requestStream.Close();
// Make the request to the Exchange server and get the response.
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
// If the response is okay, create an XML document from the reponse
// and process the request.
if (webResponse.StatusCode == HttpStatusCode.OK)
{
var responseStream = webResponse.GetResponseStream();
var responseEnvelope = XElement.Load(responseStream);
// After creating a memory stream containing the contents of the
// attachment, this method writes the XML document to the trace output.
// Your service would perform it's processing here.
if (responseEnvelope != null)
{
var processResult = ProcessXmlResponse(responseEnvelope);
attachmentNames.Add(string.Format("{0} {1}", attachment.name, processResult));
}
// Close the response stream.
responseStream.Close();
webResponse.Close();
}
// If the response is not OK, return an error message for the
// attachment.
else
{
var errorString = string.Format("Attachment \"{0}\" could not be processed. " +
"Error message: {1}.", attachment.name, webResponse.StatusDescription);
attachmentNames.Add(errorString);
}
attachmentsProcessedCount++;
}
// Return the names and number of attachments processed for display
// in the add-in UI.
var response = new AttachmentSampleServiceResponse();
response.attachmentNames = attachmentNames.ToArray();
response.attachmentsProcessed = attachmentsProcessedCount;
return response;
}
// This method processes the response from the Exchange server.
// In your application the bulk of the processing occurs here.
private string ProcessXmlResponse(XElement responseEnvelope)
{
//Refer: https://github.com/Nymann74/ewpdemoapp/blob/a71ef41d2cd42e2c17b8ace2ac5b21d08bae2722/EWPDemoApp/Program.cs#L287
// First, check the response for web service errors.
IEnumerable<XElement> errorCodes = from errorCode in responseEnvelope.Descendants
("{http://schemas.microsoft.com/exchange/services/2006/messages}ResponseCode")
select errorCode;
// Return the first error code found.
foreach (var errorCode in errorCodes)
{
if (errorCode.Value != "NoError")
{
return string.Format("Could not process result. Error: {0}", errorCode.Value);
}
}
// No errors found, proceed with processing the content.
// First, get and process file attachments.
var fileAttachments = from fileAttachment in responseEnvelope.Descendants
("{http://schemas.microsoft.com/exchange/services/2006/types}FileAttachment")
select fileAttachment;
foreach (var fileAttachment in fileAttachments)
{
var fileContent = fileAttachment.Element("{http://schemas.microsoft.com/exchange/services/2006/types}Content");
var fileData = System.Convert.FromBase64String(fileContent.Value);
//var s = new MemoryStream(fileData);
// Process the file attachment here.
File.WriteAllBytes(attachmentName, fileData);
}
// Second, get and process item attachments.
var itemAttachments = from itemAttachment in responseEnvelope.Descendants
("{http://schemas.microsoft.com/exchange/services/2006/types}ItemAttachment")
select itemAttachment;
foreach (var itemAttachment in itemAttachments)
{
var message = itemAttachment.Element("{http://schemas.microsoft.com/exchange/services/2006/types}Message");
if (message != null)
{
// Process a message here.
break;
}
var calendarItem = itemAttachment.Element("{http://schemas.microsoft.com/exchange/services/2006/types}CalendarItem");
if (calendarItem != null)
{
// Process calendar item here.
break;
}
var contact = itemAttachment.Element("{http://schemas.microsoft.com/exchange/services/2006/types}Contact");
if (contact != null)
{
// Process contact here.
break;
}
var task = itemAttachment.Element("{http://schemas.microsoft.com/exchange/services/2006/types}Tontact");
if (task != null)
{
// Process task here.
break;
}
var meetingMessage = itemAttachment.Element("{http://schemas.microsoft.com/exchange/services/2006/types}MeetingMessage");
if (meetingMessage != null)
{
// Process meeting message here.
break;
}
var meetingRequest = itemAttachment.Element("{http://schemas.microsoft.com/exchange/services/2006/types}MeetingRequest");
if (meetingRequest != null)
{
// Process meeting request here.
break;
}
var meetingResponse = itemAttachment.Element("{http://schemas.microsoft.com/exchange/services/2006/types}MeetingResponse");
if (meetingResponse != null)
{
// Process meeting response here.
break;
}
var meetingCancellation = itemAttachment.Element("{http://schemas.microsoft.com/exchange/services/2006/types}MeetingCancellation");
if (meetingCancellation != null)
{
// Process meeting cancellation here.
break;
}
}
return string.Empty;
}
private const string GetAttachmentSoapRequest =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""https://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""https://www.w3.org/2001/XMLSchema""
xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:t=""http://schemas.microsoft.com/exchange/services/2006/types"">
<soap:Header>
<t:RequestServerVersion Version=""Exchange2013"" />
</soap:Header>
<soap:Body>
<GetAttachment xmlns=""http://schemas.microsoft.com/exchange/services/2006/messages""
xmlns:t=""http://schemas.microsoft.com/exchange/services/2006/types"">
<AttachmentShape/>
<AttachmentIds>
<t:AttachmentId Id=""{0}""/>
</AttachmentIds>
</GetAttachment>
</soap:Body>
</soap:Envelope>";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment