Резюме:
У меня проблемы с подключением к exchange 2007 mailbox
, на котором запущен FBA с моим кодом C # с использованием webdav.
подробности:
Этот код ниже должен работать с сервером Exchange 2007, подключаться и читать электронную почту из почтового ящика.
Я пробовал EWS, но это не имело смысла, и я не мог заставить его работать.
Ниже мой код. Я использую URL-адрес Outlook для получения файлов cookie, необходимых для входа через webdav на URL-адрес обмена.
Ошибка:
440 login timeout on the request.
Область, где ломается мой код:
Response = (HttpWebResponse)Request.GetResponse();
Код:
namespace logintomailbox
{
class Program
{
#region auth dont exapnd
//Authentication to exchange 2007 with webdav and filebasedauth (FBA) in C#
internal static string dUser = "user";
internal static string dDomain = "domain";
internal static string dPassword = "password";
#endregion
internal static string MailBoxAliasName = "mailbox;
internal static string ExchangeServerName = "appews.host.com";
internal static string outlookServerName = "outlook.host.com";
internal static string ReadAttachments = "1"; //1 means read attachments, 0 means dont
internal static string MailBoxEarliestDateToRead = "2011-01-05T00:00:00.000Z";//date of emails to read from
static void Main(string[] args)
{
//FBA code
//once i get a 302 response code i am authenticated
DoExchangeFBA("https://" + outlookServerName, dDomain + "/" + dUser, dPassword);
//login via webdav
QueryMailBoxViaDAV();
//exit application
//ExitProgram((int)ExitReturnCodes.NormalShutdown);
}
private static void QueryMailBoxViaDAV()
{
//create http web request object
System.Net.HttpWebRequest Request;
//Request.CookieContainer = newCookieContainer();
//create http web response object
System.Net.WebResponse Response;
//create needed components of web request/response
byte[] bytes = null;
System.IO.Stream RequestStream = null;
System.IO.Stream ResponseStream = null;
XmlDocument ResponseXmlDoc = null;
string strRootURI = null;
//check if exchange server is 2007 or 2003
if (ExchangeServerName == "appews.host.com")
{
//exchange 2007
strRootURI = "https://" + ExchangeServerName + "/exchange/" + MailBoxAliasName;
}
else
{
//exchange 2003
//example of previously used url for exchange 2003 mailboxes
strRootURI = "https://" + ExchangeServerName + "/exchange/" + MailBoxAliasName + "/Inbox";
}
//begin webdav query
string strQuery = "<?xml version=\"1.0\"?><D:searchrequest xmlns:D=\"DAV:\" >"
+ "<D:sql>SELECT \"DAV:displayname\", "
+ "\"urn:schemas:mailheader:message-id\", "
+ "\"urn:schemas:mailheader:date\", "
+ "\"urn:schemas:mailheader:from\", "
+ "\"urn:schemas:mailheader:to\", "
+ "\"urn:schemas:mailheader:subject\", "
+ "\"urn:schemas:httpmail:hasattachment\", "
+ "\"urn:schemas:httpmail:textdescription\" "
+ " FROM \"" + strRootURI + "\""
+ "WHERE \"DAV:ishidden\" = false AND \"DAV:isfolder\" = false "
+ "AND \"urn:schemas:mailheader:date\" > CAST(\"" + MailBoxEarliestDateToRead.ToString() + "\" as \"dateTime.tz\")"
+ "</D:sql></D:searchrequest>";
//build http web request
Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strRootURI);
Request.KeepAlive = false;
Request.Credentials = new System.Net.NetworkCredential(
dUser,
dPassword,
dDomain);
Request.Method = "SEARCH";
//now that everything is created try sending a request
try
{
bytes = Encoding.UTF8.GetBytes((string)strQuery);
Request.ContentLength = bytes.Length;
RequestStream = Request.GetRequestStream();
RequestStream.Write(bytes, 0, bytes.Length);
RequestStream.Close();
Request.ContentType = "text/xml";
Request.KeepAlive = true;
Response = (HttpWebResponse)Request.GetResponse();
ResponseStream = Response.GetResponseStream();
ResponseXmlDoc = new XmlDocument();
ResponseXmlDoc.Load(ResponseStream);
ResponseStream.Close();
Response.Close();
Console.WriteLine("Authentication Successful");
Console.ReadLine();
}
//catch all exceptions and sent to console if they occur
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
Console.ReadLine();
}
}
private static CookieCollection DoExchangeFBA(string server, string userName, string password)
{
var uri = server + "/owa/auth/owaauth.dll";
var request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";
request.CookieContainer = new CookieContainer();
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
request.ServicePoint.Expect100Continue = false;
server = HttpUtility.UrlEncode(server);
userName = HttpUtility.UrlEncode(userName);
password = HttpUtility.UrlEncode(password);
var bodyString = "destination={0}&flags=0&username={1}";
bodyString += "&password={2}&SubmitCreds=Log+On&";
bodyString += "forcedownlevel=0&trusted=0";
bodyString = string.Format(bodyString, server,
userName, password);
var body = Encoding.ASCII.GetBytes(bodyString);
request.ContentLength = body.Length;
ServicePointManager.Expect100Continue = false;
var stream = request.GetRequestStream();
stream.Write(body, 0, body.Length);
stream.Close();
//Console.WriteLine((HttpWebResponse)request.GetResponse());
var response = (HttpWebResponse)request.GetResponse();
if (response.Cookies.Count < 2) throw
new AuthenticationException("Failed to login to OWA!");
return response.Cookies;
}
}
}