Use Exchange Web Service Managed API to retrieve max send mail size limit - exchange-server

I've been looking around for some way to use the EWS managed API to retrieve the maximum mail size limit for sending, but have not found any working solution...
So far, I've came across this link: https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-get-service-configuration-information-by-using-ews-in-exchange#code-example-get-service-configuration-information-for-mail-tips-by-using-ews
Which basically retrieves the The maximum message size in the Mail Tips. But the thing is, when I tried out the code, I got an 500 internal server error. And there doesn't seem to be a way to do this directly using the Managed API itself.
Greatly appreciate any help.
Thanks!

There is a bug in the Microsoft Sample they have modified the SOAP namespaces from http to https. Probably some editor thought they where doing the correct thing without understanding how XML schema's work. But a working sample is
private static void GetServiceConfiguration()
{
// XML for the GetServiceConfiguration request SOAP envelope for mail tips configuration information.
const string getServiceConfigurationRequest =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\"\n" +
" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" \n" +
" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <soap:Header>\n" +
" <t:RequestServerVersion Version=\"Exchange2013\" />\n" +
" </soap:Header>\n" +
" <soap:Body>\n" +
" <m:GetServiceConfiguration>\n" +
" <m:ActingAs>\n" +
" <t:EmailAddress>user#domain.com</t:EmailAddress>\n" +
" <t:RoutingType>SMTP</t:RoutingType>\n" +
" </m:ActingAs>\n" +
" <m:RequestedConfiguration>\n" +
" <m:ConfigurationName>MailTips</m:ConfigurationName>\n" +
" </m:RequestedConfiguration>\n" +
" </m:GetServiceConfiguration>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
// Encoded GetServiceConfiguration operation request.
byte[] payload = System.Text.Encoding.UTF8.GetBytes(getServiceConfigurationRequest);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://outlook.office365.com/ews/exchange.asmx");
request.AllowAutoRedirect = false;
request.Credentials = new NetworkCredential("user#domain.com", "blah");
request.Method = "POST";
request.ContentType = "text/xml";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";
Stream requestStream = request.GetRequestStream();
requestStream.Write(payload, 0, payload.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine("You will need to parse this response to get the configuration information:\n\n" + responseFromServer);
reader.Close();
responseStream.Close();
}
else
throw new WebException(response.StatusDescription);
}
catch (WebException e)
{
Console.WriteLine(e.Message);
}
I've also added in a useragent as this can sometimes also cause the code to fail if useragent restriction have been set. But you should also switch to using OAuth if you are using this against Office365.

Related

response from ajax HttpURLConnection POST is getting encoded

I'm using the HttpURLConnection POST to get the response. Im able to get the responsecode 200 but the responseString is getting encoded as below::
���������RP�b��%+c//17�Wr
��u���v����QJ�r��-�N�9���
here is the code I'm using::
public static String getPOSTAJAX(String getURL,String impersonationID,String getPOSTParameters)
{
// get Impersonation ID
String getimpersonationID = "bearer "+impersonationID;
String getResponseline = "";
String getPOSTResponse = null;
String postCookies = "sid="+impersonationID;
try
{
//Open HttpURLConnection
URL url = new URL(getURL);
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
//add request header
if (impersonationID != null && impersonationID != " ") {
urlConn.setRequestProperty("Authorization", getimpersonationID);
urlConn.setRequestProperty("Accept-Encoding","gzip, deflate");
urlConn.setRequestProperty("Cookie", postCookies);
}
urlConn.setRequestProperty("Accept","application/json,text/plain,*/*");
urlConn.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
urlConn.setRequestProperty("Connection", "keep-alive");
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.94 Safari/537.36");
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Length", String.valueOf(getPOSTParameters.getBytes().length));
urlConn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//send the POSt Request
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
DataOutputStream writeRequest = new DataOutputStream(urlConn.getOutputStream());
writeRequest.writeBytes(getPOSTParameters);
writeRequest.flush();
writeRequest.close();
//To get the Response Codes
int responseCode = urlConn.getResponseCode();
logger.debug("\nSending 'POST' request to URL::" +url);
logger.debug("Post parameters ::"+getPOSTParameters);
logger.debug("Response Code ::" + responseCode);
//parse the response
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), Charset.forName("UTF-8")));
while((getResponseline = reader.readLine()) != null)
{
builder.append(getResponseline);
builder.append("\n");
}
reader.close();
getPOSTResponse = builder.toString();
//logger.debug("\n "+getPOSTResponse);
//Disconnect the connection
urlConn.disconnect();
}
catch (IOException ioe) {
logger.error("\n"+ioe);
}
return getPOSTResponse;
}
can anyone suggest how to decode the response?
Instead of using InputStreamReader,I would suggest to use InflaterInputStream class,which can be used to uncompress data.
StringBuilder builder = new StringBuilder();
InflaterInputStream in = new InflaterInputStream(urlConn.getInputStream()), new Inflater(true));
int i;
while((i=in.read())!=-1){
builder.append(i);
}
getPOSTResponse = builder.toString();
I 've had the same problem too and I removed all request properties except Content-Type, and now it is working.
Donno how/why it works now.

Tile notification for windows phone - invalid XML payload -

I send two push notifications a toast and a tile (just a count)
the toast gets received:
<?xml version="1.0" encoding="UTF-8"?><wp:Notification xmlns:wp="WPNotification"><wp:Toast><wp:Text1></wp:Text1><wp:Text2>asdf</wp:Text2><wp:Param></wp:Param></wp:Toast></wp:Notification>
the tile does not:
<?xml version="1.0" encoding="UTF-8"?><wp:Notification xmlns:wp="WPNotification"><wp:Tile><wp:BackgroundImage></wp:BackgroundImage><wp:Count>122</wp:Count><wp:Title></wp:Title><wp:BackBackgroundImage></wp:BackBackgroundImage><wp:BackTitle></wp:BackTitle><wp:BackContent></wp:BackContent></wp:Tile></wp:Notification>
This is the xml i provide and I keep getting format errors. Is there something wrong in the format?
Your tile format should be like
string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Tile>" +
"<wp:BackgroundImage>" + TextBoxBackgroundImage.Text + "</wp:BackgroundImage>" +
"<wp:Count>" + TextBoxCount.Text + "</wp:Count>" +
"<wp:Title>" + TextBoxTitle.Text + "</wp:Title>" +
"<wp:BackBackgroundImage>" + TextBoxBackBackgroundImage.Text + "</wp:BackBackgroundImage>" +
"<wp:BackTitle>" + TextBoxBackTitle.Text + "</wp:BackTitle>" +
"<wp:BackContent>" + TextBoxBackContent.Text + "</wp:BackContent>" +
"</wp:Tile> " +
"</wp:Notification>";
Sending tile notification code.It will work for me. If any query than let me know
protected void ButtonSendTile_Click(object sender, EventArgs e)
{
try
{
// Get the Uri that the Microsoft Push Notification Service returns to the Push Client when creating a notification channel.
// Normally, a web service would listen for Uri's coming from the web client and maintain a list of Uri's to send
// notifications out to.
string subscriptionUri = TextBoxUri.Text.ToString();
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// We will create a HTTPWebRequest that posts the tile notification to the Microsoft Push Notification Service.
// HTTP POST is the only allowed method to send the notification.
sendNotificationRequest.Method = "POST";
// The optional custom header X-MessageID uniquely identifies a notification message.
// If it is present, the // same value is returned in the notification response. It must be a string that contains a UUID.
// sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
// Create the tile message.
string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Tile>" +
"<wp:BackgroundImage>" + TextBoxBackgroundImage.Text + "</wp:BackgroundImage>" +
"<wp:Count>" + TextBoxCount.Text + "</wp:Count>" +
"<wp:Title>" + TextBoxTitle.Text + "</wp:Title>" +
"<wp:BackBackgroundImage>" + TextBoxBackBackgroundImage.Text + "</wp:BackBackgroundImage>" +
"<wp:BackTitle>" + TextBoxBackTitle.Text + "</wp:BackTitle>" +
"<wp:BackContent>" + TextBoxBackContent.Text + "</wp:BackContent>" +
"</wp:Tile> " +
"</wp:Notification>";
// Sets the notification payload to send.
byte[] notificationMessage = Encoding.Default.GetBytes(tileMessage);
// Sets the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "token");
sendNotificationRequest.Headers.Add("X-NotificationClass", "1");
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
// Display the response from the Microsoft Push Notification Service.
// Normally, error handling code would be here. In the real world, because data connections are not always available,
// notifications may need to be throttled back if the device cannot be reached.
TextBoxResponse.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
}
catch (Exception ex)
{
TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
}
}

Windows Phone 7.5 POST method return remote server not found

I'm trying to make a POST but every time returns an error saying
"The remote server returned an error: NotFound."
I'm using Firebug extension of Firefox to get all the necessary parameters of the POST method but firebug says
"... Firebug request size limit has been reached by Firebug. ..."
. Also wireshark says more or less the same thing.
I don't know if I need to specify (on windows phone 7 HttpWebRequest) some extra parameters on header because of the long POST method.
This is my code:
private void GetResponseCallbackAGCP(IAsyncResult asynchronousResult)
{
Uri url = new Uri("http://publico.agcp.ipleiria.pt/Paginas/ScheduleRptCursosSemanalPublico.aspx");
postData = "MSO_PageHashCode=" + _MSO_PageHashCode +
"&__SPSCEditMenu=" + ___SPSCEditMenu +
"&MSOWebPartPage_PostbackSource=" +
"&MSOTlPn_SelectedWpId=" +
"&MSOTlPn_View=0" +
"&MSOTlPn_ShowSettings=" + _MSOTlPn_ShowSettings +
"&MSOGallery_SelectedLibrary=" +
"&MSOGallery_FilterString=" +
"&MSOTlPn_Button=" + _MSOTlPn_Button +
"&MSOAuthoringConsole_FormContext=" +
"&MSOAC_EditDuringWorkflow=" +
"&MSOSPWebPartManager_DisplayModeName=" + _MSOSPWebPartManager_DisplayModeName +
"&__EVENTTARGET=" + _eventTarget +
"&__EVENTARGUMENT=" + _eventArg +
"&MSOWebPartPage_Shared=" +
"&MSOLayout_LayoutChanges=" +
"&MSOLayout_InDesignMode=" +
"&MSOSPWebPartManager_OldDisplayModeName=" + _MSOSPWebPartManager_OldDisplayModeName +
"&MSOSPWebPartManager_StartWebPartEditingName=" + _MSOSPWebPartManager_StartWebPartEditingName +
"&__LASTFOCUS=" +
"&__REQUESTDIGEST=" + ___REQUESTDIGEST +
"&__VIEWSTATE=" + _viewState +
"&__EVENTVALIDATION=" + _eventEval +
"&ctl00%24ctl12%24ctl00=http%3A%2F%2Fspserver%3A7250" +
"&ctl00%24PlaceHolderAGCPUO%24ddlUO=" + escolaSelected +
"&ctl00%24PlaceHolderAGCPUO%24ddlAnosLectivos=" + anoLectivoSelected +
"&ctl00%24PlaceHolderAGCPUO%24ddlPeriodos=" + periodoSelected +
"&ctl00%24PlaceHolderMain%24ddlCursos=" + cursoSelected +
"&ctl00%24PlaceHolderMain%24ddlAnosCurr=" + anoCurricularSelected +
"&ctl00%24PlaceHolderMain%24ddlPlanos=" + planoSelected +
"&ctl00%24PlaceHolderMain%24ddlRamos=" + troncoSelected +
"&ctl00%24PlaceHolderMain%24ddlTurmas=" + turmaSelected +
"&ctl00%24PlaceHolderMain%24txtObservacoesHor=" +
"&ctl00%24PlaceHolderMain%24ddlZoom=1250" +
"&ctl00%24PlaceHolderMain%24ddlSemanas=" + semanaSelected +
"&ctl00_PlaceHolderMain_DayPilotCalendar1_vsupdate=" +
"&ctl00_PlaceHolderMain_DayPilotCalendar1_scrollpos=" +
"&ctl00_PlaceHolderMain_DayPilotCalendar1_select=" +
"&__spDummyText1=__spDummyText1&__spDummyText2=__spDummyText2";
cc = new CookieContainer();
webRequest2 = (HttpWebRequest)WebRequest.Create(url);
webRequest2.Method = "POST";
webRequest2.ContentType = "application/x-www-form-urlencoded";
webRequest2.CookieContainer = cc;
webRequest2.BeginGetRequestStream(new AsyncCallback(GetRequestCallback), webRequest2);
}
private void GetRequestCallback(IAsyncResult asynchronousResult)
{
var request = asynchronousResult.AsyncState as HttpWebRequest;
StreamWriter stream = new StreamWriter(request.EndGetRequestStream(asynchronousResult));
stream.Write(postData);
stream.Flush();
stream.Close();
request.BeginGetResponse(AuthCallback, request);
}
private void AuthCallback(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); //RETURNS an error saying "WebException was unhandle. The remote server returned an error: NotFound."
using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
{
//string resultString = streamReader1.ReadToEnd();
var info = streamReader1.ReadToEnd();
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
webView.NavigateToString(info);
});
}
}
Thanks in advance!
Try using RestSharp, it greatly simplifies the Http stuff. I have been using RestSharp in all my WP7 Projects.
http://restsharp.org/
This Exception also come due to Firewall just turn off firewall
Go Control Panel\All Control Panel Items\Windows Firewall\Customize Settings
and turn off firewall.

Sending Form data alongwith File Data for Content Type "application/vnd.ms-project" for MPP files

I need to send some post data along with a file stream. I'm using the following code.
This code is taken from
http://technet.rapaport.com/Info/LotUpload/SampleCode/Full_Example.aspx.
private Stream GetPostStream(string filePath, Dictionary<string, string> paramMap, string boundary) {
Stream postDataStream = new System.IO.MemoryStream();
//adding form data
string formDataHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
"Content-Disposition: form-data; name=\"{0}\";" + Environment.NewLine + Environment.NewLine + "{1}";
foreach (KeyValuePair<string, string> pair in paramMap)
{
byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formDataHeaderTemplate, pair.Key, pair.Value));
postDataStream.Write(formItemBytes, 0, formItemBytes.Length);
}
//adding file data
FileInfo fileInfo = new FileInfo(filePath);
string fileHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
Environment.NewLine + "Content-Type: application/vnd.ms-project" + Environment.NewLine + Environment.NewLine;
byte[] fileHeaderBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(fileHeaderTemplate, "UploadMPPFile", fileInfo.FullName));
postDataStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);
FileStream fileStream = fileInfo.OpenRead();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
postDataStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] endBoundaryBytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "--");
postDataStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
return postDataStream;
}
On the server side which is on JAVA, I'm using MPXJ 3rd party library to read the the file data. However, there I'm encountering the following exception. It reports some mismatch error in Header signature.
Nested exception is: net.sf.mpxj.MPXJException: Error reading file]
with root cause java.io.IOException: Invalid header signature; read
0x2D2D2D2D2D2D0A0D, expected 0xE11AB1A1E011CFD0 at
org.apache.poi.poifs.storage.HeaderBlockReader.(HeaderBlockReader.java:125)
at
org.apache.poi.poifs.filesystem.POIFSFileSystem.(POIFSFileSystem.java:153)
at net.sf.mpxj.mpp.MPPReader.read(MPPReader.java:84)
Could anyone please help me out with this situation and suggest some solutions!
Thanks a lot.
Looks suspiciously like the receiving end is not separating the header data you are writing to the stream from the payload data. Might be worth trying the following:
Validate that you are reading the MPP file correctly by replacing the call to postDataStream.Write with a write to a local file stream. Validate that the content of the file you create is identical to the file you are reading.
Replace the receiving code on the server side with something which simply echos the received data to a file so you can validate what is being received.
Update the existing receiving code to write the extracted header data and the payload data to separate files to validate that both are being received correctly and that the payload filematches what is being sent from the client.

How can I get the Exchange Server programmatically from my App(C#)

Currently I can send email successfully through WebDAV with C#, but there is a shortage in my App that I have hard-code the Exchange Server of my outlook, so it might only works for me, if it were moved to another PC and use another outlook account, it might not work because the Exchange Server for this outlook account might not the same as mine(that's beacuse our company for different email account might assign different Exchange server), so my question is that how can I get the Exchange Server for the current Email accout dynamically. In fact I can get this Exchange Server from the outlook client when I clicked the menu item to add a new Outlook Account, but dose there exist any API for me to get this Exchange Server programmatically such as with C#?
In fact I use the following code to send Email:
using System;
using System.Net;
using System.IO;
namespace WebDavNET
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
try
{
// TODO: Replace with the name of the computer that is running Exchange 2000.
string strServer = "ExchServe";
// TODO: Replace with the sender's alias.
string strSenderAlias = "sender";
// TODO: Replace with the sender's e-mail address.
string strFrom = "sender#example.com";
// TODO: Replace with the recipient's e-mail address.
string strTo = "recipient#example.com";
string strSubject = "Send Using HttpWebRequest";
string strBody = "Hello World";
string sUri;
sUri = "http://" + strServer + "/Exchange/" + strSenderAlias;
sUri = sUri + "/%23%23DavMailSubmissionURI%23%23/";
System.Uri myUri = new System.Uri(sUri);
HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(myUri);
string sQuery;
DateTime mySentTime = new DateTime();
sQuery = "From: " + strFrom + "\n" +
"To: " + strTo + "\n" +
"Subject: " + strSubject + "\n" +
"Date: " + DateTime.Now.ToString() + "\n" +
"X-Mailer: My DAV mailer" + "\n" +
"MIME-Version: 1.0" + "\n" +
"Content-Type: text/plain;" + "\n" +
"Charset = \"iso-8859-1\"" + "\n" +
"Content-Transfer-Encoding: 7bit" + "\n" + "\n" +
strBody;
// Set the credentials.
// TODO: Replace with the appropriate user credential.
NetworkCredential myCred = new NetworkCredential(#"DomainName\User", "Password");
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myCred);
HttpWRequest.Credentials = myCredentialCache;
// Set the headers.
HttpWRequest.Headers.Set("Translate", "f");
HttpWRequest.ContentType = "message/rfc822";
HttpWRequest.ContentLength = sQuery.Length;
//Set the request timeout to 5 minutes.
HttpWRequest.Timeout = 300000;
// Set the request method.
HttpWRequest.Method = "PUT";
// Store the data in a byte array.
byte[] ByteQuery = System.Text.Encoding.ASCII.GetBytes(sQuery);
HttpWRequest.ContentLength = ByteQuery.Length;
Stream QueryStream = HttpWRequest.GetRequestStream();
// write the data to be posted to the Request Stream
QueryStream.Write(ByteQuery,0,ByteQuery.Length);
QueryStream.Close();
// Send the request and get the response.
HttpWebResponse HttpWResponse = (HttpWebResponse)HttpWRequest.GetResponse();
// Get the Status code.
int iStatCode = (int)HttpWResponse.StatusCode;
string sStatus = iStatCode.ToString();
Console.WriteLine("Status Code: {0}", sStatus);
// Get the request headers.
string sReqHeaders = HttpWRequest.Headers.ToString();
Console.WriteLine(sReqHeaders);
// Read the response stream.
Stream strm = HttpWResponse.GetResponseStream();
StreamReader sr = new StreamReader(strm);
string sText = sr.ReadToEnd();
Console.WriteLine("Response: {0}", sText);
// Close the stream.
strm.Close();
// Clean up.
myCred = null;
myCredentialCache = null;
HttpWRequest = null;
HttpWResponse = null;
QueryStream = null;
strm = null;
sr = null;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
}
As you can see in the code there is a variable named "strServer", In my App I just hard-code my Exchange Server for this variable, so my question is that dose there exist any API for me to get the Exchange Server dynamically for the specific outlook account?
Thanks!
You can use EWS(exchange Web Services) too. here is the link
You can use XML creator for creating items or requests required for operations in the link. Just go through the operations given on the link.

Resources