How to get Exchange Online Folders

Standard

You can get all folders based in a criteria, this is useful because it can be queried by a SearchFilter. In this case I’m only get Folders that have at least 1 message because operator is SearchFilter.IsGreaterThan

 

SearchFilter searchFilter = new SearchFilter.IsGreaterThan
(FolderSchema.TotalCount, 0);
 
Unlike messages, in folders, you can use Deep Transversal’s, this means that you can get all Sub Folders on the fly.
 
 

view.Traversal = FolderTraversal.Deep;

 

As always you have to use an Object type of ExchangeService(), see the GetBinding() Method

 

Main Procedure

 

// Create a view with a page size of 10 or number you want.
FolderView view = new FolderView(10)

{
   
PropertySet = new PropertySet
     (BasePropertySet.IdOnly) { FolderSchema.DisplayName }
};

// Identify the properties to return in the results set.
// Return only folders that contain items.
SearchFilter searchFilter = new SearchFilter.IsGreaterThan

  (FolderSchema.TotalCount, 0);

// Unlike FindItem searches, folder searches can be deep traversals.
view.Traversal = FolderTraversal.Deep;

// Send the request to search the mailbox and get the results.
FindFoldersResults findFolderResults = service.FindFolders

  (WellKnownFolderName.Root, searchFilter, view);

// Process each item.
foreach (Folder myFolder in findFolderResults.Folders)

{
    // Go get myFolder.Id, MyFolder.DisplayName etc…
}

// Determine whether there are more folders to return.
if (findFolderResults.MoreAvailable)

{
   
// Make recursive calls with offsets set for the FolderView

    // to get the remaining folders in the result set for Paging.
}

Read message body with InLine Attachment’s and render it

Standard

In order to use this code you will need to get the GetBinding() method and understand how to get a message item UniqueId

I am catching the Inline attachments and converting to Base64, should be fine for you

using Microsoft.Exchange.WebServices.Autodiscover;
using Microsoft.Exchange.WebServices.Data;
using BodyType = Microsoft.Exchange.WebServices.Data.BodyType;/// <summary>

/// Les the menssagem por id.
/// </summary>
/// <param name="messId">The mess id.</param>
/// <returns></returns>
public static string LeMenssagemPorId(string messId)
{
PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties)
{
    RequestedBodyType = BodyType.HTML
};
Item mess = Item.Bind(GetBinding(), messId, psPropSet);
mess.Body.BodyType = BodyType.HTML;

string sHTMLCOntent = mess.Body.Text;

FileAttachment[] attachments = null;

if (mess.Attachments.Count != 0)
{
    attachments = new FileAttachment[mess.Attachments.Count];
    for (int i = 0; i < mess.Attachments.Count; i++)
    {
        try
        {
            if (mess.Attachments[i].IsInline)
            {
                string sType = mess.Attachments[i].ContentType.ToLower();
                if (sType.Contains("image"))
                {
                    attachments[i] = (FileAttachment)mess.Attachments[i];
                    attachments[i].Load();
                    string sId = attachments[i].ContentId;
                    sType = sType.Replace("image/", "");
                    string oldString = "cid:" + sId;
                    string imagem = 
                        Convert.ToBase64String(attachments[i].Content);
                    sHTMLCOntent = sHTMLCOntent.Replace(oldString, 
                        "data:image/" + sType + ";base64," + imagem);
                }
            }
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write("Erro: " + ex.Message);
        }
    }
}

Get Attachments from a Message

Standard

In order to use this code you will need to get the GetBinding() method and understand how to get a message item UniqueId

GET ATTACHMENT’S COLLECTION

// Bind to an existing MyMessage item, requesting its 
//Id property plus its attachments collection.
EmailMessage myMessage = EmailMessage.Bind(GetBinding(),
    new ItemId(“Your message unique id”),
        new PropertySet(BasePropertySet.IdOnly,
            ItemSchema.Attachments));

ITERATE THROUGH ATTACHMENT’S COLLECTION

// Iterate through the attachments collection and load each attachment.
foreach (Attachment attachment in myMessage.Attachments)
{
}

GET THE FILE OR ITEM ATTACHMENT INTO MEMORY

if (attachment is FileAttachment)
{
    //If it's file attachment
    FileAttachment fileAttachment = attachment as FileAttachment;
    //Load the file attachment into memory
    fileAttachment.Load();
}
else // Attachment is an item attachment.
{
    //If it's item attachment 
    ItemAttachment itemAttachment = attachment as ItemAttachment;
    //Load the item attachment into memory
    itemAttachment.Load();
}

Send a Message with Recipients and Attachments

Standard

You can use in the bellow code the GetBinding() Method in order to pass as ExchangeService

Attachments are the Full Path to file in HDD

Body is HTML or Plain Text

Recipients are valid E-Mails

CODE – Return true if sent

/// <summary>
/// Envia Mensagem.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="subject">The subject.</param>
/// <param name="body">The body.</param>
/// <param name="mailTo">The mail to.</param>
/// <param name="mailCc"></param>
/// <param name="mailBcc"></param>
/// <param name="attachments"></param>
public static bool SendNewMessage(ExchangeService service, 
                  string subject, string body, 
                  List<string> mailTo, 
                  List<string> mailCc, 
                  List<string> mailBcc, 
                  List<string> attachments)
{
    // Create an e-mail message and identify the Exchange service.
    EmailMessage message = new EmailMessage(service)
    {
        /* Subject*/
        Subject = subject, /* Body*/
        Body = new MessageBody(body)
    };

    // Recipients
    foreach (string recipientes in mailTo)
    {
        message.ToRecipients.Add(recipientes);
    }

    // Recipients
    foreach (string recipientes in mailCc)
    {
        message.CcRecipients.Add(recipientes);
    }

    // Recipients
    foreach (string recipientes in mailBcc)
    {
        message.BccRecipients.Add(recipientes);
    }

    // Recipients
    foreach (string att in attachments)
    {
        message.Attachments.AddFileAttachment(att);
    }
    // Send the mail. This makes a trip to the EWS server.
    message.SendAndSaveCopy();
    return true;
}