/// <summary> /// Read emails from the EWS account /// </summary> /// <param name="email">email</param> /// <returns>All Emails from Inbox as a List of Messages</returns> /// <exception cref="ArgumentNullException"></exception> public static List <EmailMessage> ReadEmails(Email email) { if (email == null) { throw new ArgumentNullException(); } ExchangeService service = ExchangeServiceUtil.GetExchangeService(email.EmailId, email.Password, email.Token); try { service.Url = new Uri(email.ExchangeUrl ?? "https://outlook.office365.com/ews/exchange.asmx"); service.TraceEnabled = false; //By Default, exchange won't return all the properties of an email. We are specifying here to get Email Body also. //Body is in HTML format. TextBody contains the actual text message PropertySet propSet = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.TextBody, ItemSchema.Body); //Setting a max emails to read per request. There might be a threshold on the number of emails to fetch in a request. ItemView view = new ItemView(1000); FindItemsResults <Item> foundItems = null; var list = new List <EmailMessage>(); do { //Get actual items from EWS inbox. foundItems = service.FindItems(WellKnownFolderName.Inbox, view); foreach (EmailMessage emailMsg in foundItems) { emailMsg.Load(propSet); //Load those extra properties like body and body text list.Add(emailMsg); } //Set the offset for next page results view.Offset += foundItems.Items.Count; }while (foundItems.MoreAvailable == true); //If more items are there, continue the loop. return(list); } catch { //Log the error throw; } }
/// <summary> /// Send an Email with the given Email Account details /// </summary> /// <param name="email">Email</param> /// <exception cref="ArgumentNullException">Throw when Email Id or Password is Invalid</exception> /// <exception cref="SmtpException"></exception> /// <exception cref="AutodiscoverRemoteException"></exception> public static void SendEmail(Email email) { if (email == null) { throw new ArgumentNullException(); } try { var service = ExchangeServiceUtil.GetExchangeService(email.EmailId, email.Password, email.Token); var serviceUrl = email.ExchangeUrl ?? "https://outlook.office365.com/ews/exchange.asmx"; service.Url = new Uri(serviceUrl); EmailMessage emailMessage = new EmailMessage(service) { Subject = email.Subject, Body = new MessageBody(BodyType.HTML, email.Body), }; emailMessage.ToRecipients.AddRange(email.ToRecipients); emailMessage.Send(); } catch (SmtpException exception) { string msg = $"Mail could not be sent (SmtpException):{exception.Message}"; //Log error message throw; } catch (AutodiscoverRemoteException exception) { string msg = $"Mail cannot be sent(AutodiscoverRemoteException): {exception.Message} "; //Log error message throw; } }