Regarding EWS web service for office 365 - c#

I am using EWS web services for fetching emails form office 365 account.
I am getting this error
The Autodiscover service couldn't be located.
I have written this code.
ExchangeService service = new ExchangeService(userData.Version);
if (listener != null)
{
service.TraceListener = listener;
service.TraceFlags = TraceFlags.All;
service.TraceEnabled = true;
}
service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password);
service.UseDefaultCredentials = false;
if (userData.AutodiscoverUrl == null)
{
Console.Write(string.Format("Using Autodiscover to find EWS URL for {0}. Please wait... ", userData.EmailAddress));
service.AutodiscoverUrl(userData.EmailAddress);
userData.AutodiscoverUrl = service.Url;
Console.WriteLine("Complete");
}
Please check what i am doing wrong.
Thanks

Try the following:
ExchangeService service = new ExchangeService();
service.TraceEnabled = true;
service.Credentials = new WebCredentials(User, Pwd);
service.AutodiscoverUrl(User, RedirectionUrlValidationCallback);
service.TraceEnabled = true;

Related

How to get Email ConversationId by EWS after send email

I want to get the email's ConversationId after sending an email.
I am using Microsoft exchange web services package for sending an email.
using Microsoft.Exchange.WebServices.Data;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.UseDefaultCredentials = false;
service.Credentials = new WebCredentials('*****', '*****');
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl(emailExist.Email, RedirectionUrlValidationCallback);
EmailMessage emailMessage = new EmailMessage(service);
emailMessage.From = "abcd#xyz.com";
emailMessage.Subject = "testing email";
emailMessage.Body = new MessageBody(BodyType.HTML, "<b>Hello</b> World");
if (!string.IsNullOrEmpty(email.To))
{
var toArr = email.To.Split(',');
foreach (var toAddress in toArr)
{
emailMessage.ToRecipients.Add(toAddress.Trim());
}
}
// Send message and save copy by default to sentItems folder
emailMessage.SendAndSaveCopy();
In EWS Sends are asynchronous so you won't get back the Id of the message you just send in the Send Method. If you save the Message as a draft first before sending it that should populate both the Message and CoversationId's eg
EmailMessage em = new EmailMessage(service);
em.Subject = "Test"
em.Save();
em.Load();
Console.WriteLine(em.ConversationId.UniqueId);

Office 365 Impersonation

I'm trying to send an email from my Office 365 account while impersonating User2.
{
ExchangeService service = new ExchangeService();
string fromUserEmail = new string("User2#domain");
service.Credentials = new WebCredentials("User1#domain", "password");
service.UseDefaultCredentials = false;
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, fromUserEmail);
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
EmailMessage email = new EmailMessage(service);
email.ToRecipients.Add("someone#somewhere");
email.ReplyTo.Add(replyToEmail);
email.Subject = "HelloWorld";
email.Body = new MessageBody("Test message");
email.Send();
}
I get a System.NullReferenceException: 'Object reference not set to an instance of an object.' on email.Send(). When I comment out the service.Impersonation it works. What am I doing wrong?
Solved. I needed permission via
New-ManagementRoleAssignment -Name:User1_impersonation -Role:ApplicationImpersonation -User: "User1#domain"
I don't know why Visual Studio didn't provide a more useful error message.

Accessing room calendar in EWS returns "No mailbox with such guid"

I am trying to get the list of meetings from a room shared calendar using Microsoft Exchange (EWS) API and it's returning this error: No mailbox with such guid
var service = new ExchangeService();
service.Credentials = new NetworkCredential("username", "password");
service.Url = new Uri("exchangeUrl");
var startDate = DateTime.Today;
var endDate = DateTime.Today.AddDays(1);
var cv = new CalendarView(startDate, endDate);
var mailboxToAccess = "room_email_address#mycompany.com";
var calendarFolderId = new FolderId(WellKnownFolderName.Calendar, mailboxToAccess);
var appointments = service.FindAppointments(calendarFolderId, cv); // << Exception happens here
Any ideas what could be wrong?
Make sure that the user that you're using in
service.Credentials = new NetworkCredential("username", "password");
is a licensed user, with their own mailbox, that has been granted access to the Shared Mailbox in question.
Use this, if you're trying to access Outlook mail box from an application end.
Language:C#
service.Credentials = new NetworkCredential("username", "password");
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

How to connect to Exchange?

The simplest thing I want in my company - is to retrieve mails. I tried over Imap - no success, (ImapX not connecting at all and no error is shown) and I came to EWS.
But there is also some voo-doo magic involved.
And here is the code with some errors:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.UseDefaultCredentials = true;
service.Url = new Uri("https://some.com/EWS/Exchange.asmx"); // The request failed. Unable to connect to the remote server
var folder = Folder.Bind(service, WellKnownFolderName.Inbox);
///////////////////another try
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.UseDefaultCredentials = true;
service.AutodiscoverUrl("someone#some.com"); // Discover server not found
var folder = Folder.Bind(service, WellKnownFolderName.Inbox);
However, I'm able to connect to wsdl version:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.UseDefaultCredentials = true;
service.Url = new Uri("https://some.com:444/EWS/Services.wsdl");//Wow! It worked.
var folder = Folder.Bind(service, WellKnownFolderName.Inbox);//duh, Method Not Allowed ........
return null;
How the heck do I connect to EWS? I'm able to connect through Outlook, and aquired all this addresses from its Autodiscover.xml file of my domain account. This question blowing my head.
UPDATE
Here is example with IMAP server:
var client = new ImapX.ImapClient("imap.some.com", 993, true);
client.Connect(); //just do nothing. nothing is connected, no errors.
Make sure you have autodisocver configure for EWS webservices. Use the microsoft test connectivity tool to analyze the exchange discovery settings:
https://testconnectivity.microsoft.com/
public static class ExchangeServerService
{
// The following is a basic redirection validation callback method. It
// inspects the redirection URL and only allows the Service object to
// follow the redirection link if the URL is using HTTPS.
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
public static ExchangeService ConnectToService()
{
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.Credentials = new NetworkCredential(#"email", "password");
service.AutodiscoverUrl(#"email", RedirectionUrlValidationCallback);
return service;
}
catch (Exception ex)
{
// log exception maybe
return null;
}
}
}
Use it like:
var ESserver = ExchangeServerService.Connect();

Getting SAML token from ADFS using windows credentials

I am creating a windows 8 client app in c#.This app will use odata service of SAP. For authentication I need SAML token issued by ADFS. Is there any method to get SAML token from ADFS using windows credentials?
You can get the SAML token using the below code.
var factory = new WSTrustChannelFactory(new Microsoft.IdentityModel.Protocols.WSTrust.Bindings.UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), adfsEndpoint);
factory.Credentials.UserName.UserName = "username";
factory.Credentials.UserName.Password = "********";
factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
factory.TrustVersion = TrustVersion.WSTrust13;
WSTrustChannel channel = null;
try
{
var rst = new RequestSecurityToken
{
RequestType = WSTrust13Constants.RequestTypes.Issue,
AppliesTo = new EndpointAddress("https://yourserviceendpoint.com/"),
KeyType = KeyTypes.Bearer,
};
channel = (WSTrustChannel)factory.CreateChannel();
return channel.Issue(rst);
}
catch (Exception e)
{
return null;
}

Categories