using Microsoft.Exchange.WebServices.Data;
using MailKit;
using MailKit.Net.Imap;
using MailKit.Search;
using MailKit.Security;
using Microsoft.Identity.Client;
using Microsoft.Win32.SafeHandles;
using MimeKit;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PopClient
{
static class Program
{
#region SASMechanism Variables
static readonly string tenant = "tenant";
static readonly string smtp_server = "smtp.office365.com";
static readonly string aad_app_id = "aad_app_id";
static readonly string aad_app_secret = "aad_app_secret";
static readonly string user = "user";
static readonly string pass = "pass";
static readonly string imap_server = "outlook.office365.com";
#endregion
const string ExchangeAccount = "pass";
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#region SecurityProtocolType Setting
try
{ //try TLS 1.3
ServicePointManager.SecurityProtocol = (SecurityProtocolType)12288
| (SecurityProtocolType)3072
| (SecurityProtocolType)768
| SecurityProtocolType.Tls;
}
catch (NotSupportedException)
{
try
{ //try TLS 1.2
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072
| (SecurityProtocolType)768
| SecurityProtocolType.Tls;
}
catch (NotSupportedException)
{
try
{ //try TLS 1.1
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768
| SecurityProtocolType.Tls;
}
catch (NotSupportedException)
{ //TLS 1.0
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
}
}
}
#endregion
MainAsync().GetAwaiter().GetResult();
Console.ReadLine();
}
static async System.Threading.Tasks.Task MainAsync()
{
var cca = ConfidentialClientApplicationBuilder
.Create(aad_app_id)
.WithClientSecret(aad_app_secret)
.WithTenantId(tenant)
.Build();
var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
try
{
var authResult = await cca.AcquireTokenForClient(ewsScopes)
.ExecuteAsync();
// Configure the ExchangeService with the access token
var ewsClient = new ExchangeService();
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
ewsClient.ImpersonatedUserId =
new ImpersonatedUserId(ConnectingIdType.SmtpAddress, user);
//Include x-anchormailbox header
ewsClient.HttpHeaders.Add("X-AnchorMailbox", user);
// Make an EWS call
// Read 100 mails
foreach (EmailMessage email in ewsClient.FindItems(WellKnownFolderName.Inbox, new ItemView(10)))
{
string strFrom = "", ToRecipients = "", BccRecipients = "", CcRecipients = "", Subject = "", Body = "", TextBody = "", Attachments = "";
//email.Load(new PropertySet(EmailMessageSchema.ConversationTopic, ItemSchema.Attachments,
// ItemSchema.TextBody));
PropertySet plainTextPropertySet = new PropertySet(BasePropertySet.FirstClassProperties)
{ RequestedBodyType = BodyType.Text, };
EmailMessage emailMessage = EmailMessage.Bind(ewsClient, email.Id, plainTextPropertySet);
string body = emailMessage.Body.Text;
email.IsRead = true;
email.Update(ConflictResolutionMode.AutoResolve);
strFrom = email.From.Address;
Console.WriteLine(email.ConversationTopic);
Console.WriteLine("From : " + strFrom);
Console.WriteLine("To : " + email.ToRecipients.ToString());
Console.WriteLine("BCC : " + email.BccRecipients);
Console.WriteLine("CC : " + email.CcRecipients);
Console.WriteLine("Subject : " + email.Subject);
EmailMessage message = EmailMessage.Bind(ewsClient, new ItemId(email.Id.ToString()));
if (message.HasAttachments && message.Attachments[0] is FileAttachment)
{
FileAttachment fileAttachment = message.Attachments[0] as FileAttachment;
fileAttachment.Load(@"C:\PRAMOD\PROJECT\ReadMailOutlook\PopClient\PopClient\\Attachments\\" + fileAttachment.Name);
// lblAttach.Text = "Attachment Downloaded : " + fileAttachment.Name;
}
}
}
catch (MsalException ex)
{
Console.WriteLine($"Error acquiring access token: {ex}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex}");
}
if (System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine("Hit any key to exit...");
Console.ReadLine();
}
}
public class MailMessages
{
public MimeMessage mMessage { get; set; }
public IMailFolder imFolder { get; set; }
public UniqueId uid { get; set; }
}
}