Am using EWS API to connect Exchange server. The connection was established, but I didn’t receive any response.
Am getting exception “The response received from the service didn't contain valid XML.”
The inner Exception was “DTD is prohibited in this XML document.”
I didn’t get what is DTD?
I was getting your problem until (after MUCH trial and error):
set TraceEnabled to true, this will dump the back and forth messages to console.
I used the URL https://yourexchangeserver/EWS/Exchange.asmx
e.g. my work uses BPOS, in asia pacific region, so : https://red003.mail.apac.microsoftonline.com/EWS/Exchange.asmx
Request a specific service version e.g. ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1)
Step 1 got me past your first problem - it was giving the Outlook Web Access html page.
Step 2 let me see that it was then requesting 2010_Sp1, but that version wasn't supported.
Step 3 got "Hello world" working/sending.
Another note if you use that server, I couldn't get it to take any version except 2007 SP1, and thus, no AutoDiscovery of the URL.
public static string sendMail_BPOS_EWS()
{
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.UseDefaultCredentials = false;
service.Credentials = new WebCredentials("some_address#server.com", "password");
service.Url = new Uri("https://red003.mail.apac.microsoftonline.com/EWS/Exchange.asmx");
Console.WriteLine(service.Url);
service.TraceEnabled = true;
EmailMessage mail = new EmailMessage(service);
mail.From = new EmailAddress("from_address#server.com");
mail.ToRecipients.Add("to_address#server.com");
mail.Subject = "Email Subject";
mail.Body = "Email Body";
mail.Send();
return "sent";
}
catch (Exception ex)
{
return ex.ToString();
}
}
Related
Same piece of code works successfully in Gmail for replying messages, but in yahoo, I'm getting error.
Here is the code I've tried
Message[] messages2 = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
Message msg = messages2[i];
System.out.println("\n 1st ===> setup Mail Server Properties..");
mailServerProperties = System.getProperties();
mailServerProperties.put("mail.smtp.port", "587");
mailServerProperties.put("mail.smtp.auth", "true");
mailServerProperties.put("mail.smtp.starttls.enable", "true");
System.out.println("Mail Server Properties have been setup successfully..");
getMailSession = Session.getDefaultInstance(mailServerProperties, null);
Message replyMessage = new MimeMessage(getMailSession);
replyMessage = (MimeMessage) msg.reply(false);
replyMessage.setFrom(new InternetAddress(to));
replyMessage.setText("Thanks");
replyMessage.setReplyTo(msg.getReplyTo());
// Send the message by authenticating the SMTP server
// Create a Transport instance and call the sendMessage
Transport t = session.getTransport("smtp");
try {
//connect to the smpt server using transport instance
//change the user and password accordingly
t.connect("smtp.mail.yahoo.com",table_user, table_pass);
t.sendMessage(replyMessage,
replyMessage.getAllRecipients());
} finally {
t.close();
}
System.out.println("message replied successfully ....");
The error I'm getting:
com.sun.mail.smtp.SMTPSendFailedException: 550 Request failed; Mailbox unavailable
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1634)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:889)
at mail$8.doInBackground(mail.java:1114)
at mail$8.doInBackground(mail.java:1)
at javax.swing.SwingWorker$1.call(SwingWorker.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at javax.swing.SwingWorker.run(SwingWorker.java:334)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Please point me to the right direction ,what I'm doing wrong.
The Yahoo mail server doesn't like one of your recipients of the reply message. Try enabling JavaMail debug output and you might get more information about what's wrong.
Note also that you're creating the replyMessage by using the MimeMessage constructor, then throwing that value away and assigning it to the return value of the reply method. You can get rid of the call to the constructor, which is doing nothing.
I am getting UnAuthorized(401) Error when trying to send, or read email
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.Credentials = new WebCredentials("XXXX#YYY.COM", "XXXXXXXX");
service.AutodiscoverUrl("XXXXXX#YYYYY.com", RedirectionUrlValidationCallback);
EmailMessage email = new EmailMessage(service);
email.ToRecipients.Add("abc#yahoo.com");
email.Subject = "Testing from C#";
email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API");
email.Send();
The problem is most likely what you are passing for the WebCredentials
The credentials depend on how your Exchange/Active Directory is configured.
Try passing in the format user name, password, and domain:
service.Credentials = new WebCredentials("username", "password", "domain");
For more information see WebCredentials Constructors and Connecting to EWS
I received the following error when downloading from Box server:
InnerException {System.ArgumentException: [net_WebHeaderInvalidControlChars]
Arguments:
Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=4.7.60408.0&File=System.Net.dll&Key=net_WebHeaderInvalidControlChars
Parameter name: name
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)} System.Exception {System.ArgumentException}
Shown below is the code snippet.
using (HttpClient client = new HttpClient(handler) { MaxResponseContentBufferSize = Int32.MaxValue })
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
try
{
var fileResponse = await client.GetAsync(requestUrl, HttpCompletionOption.ResponseHeadersRead);
if (fileResponse != null && fileResponse.StatusCode == System.Net.HttpStatusCode.OK)
return await fileResponse.Content.ReadAsByteArrayAsync();
else return null;
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("Error in getAsync, " + e.StackTrace);
return null;
}
}
Note that this only happens for files with Korean (non-English) filenames and corrupted files. For image files and non-corrupted files, I was able to download successfully. (Example of corrupted file is a word or ppt file that shows an error msg when opened).
Having the same issue in windows phone 8.
I tried
HttpResponseMessage response = await httpClient.SendAsync(requestMessage);
I tried
WebClient client = new WebClient();
client.OpenReadAsync(new Uri(url,UriKind.RelativeOrAbsolute));
I tried IRestResponse from RestClient
All resulting in exception with empty value and inner exception net_WebHeaderInvalidControlChars.
The problem was that the user agent passed from windows client was not recognized server side. As a result, one from the returned response headers, was making .Net to crash in a lower level and the response could not be processed.
Adding NativeHost as the recognized UserAgent fixed the exception
I'm trying to start work with EWS using EWS-Api-2.1 nuget package. Below is simple code I'm using:
ExchangeService _service = new ExchangeService();
_service.Credentials = new WebCredentials("mail", "password");
_service.AutodiscoverUrl("mail", url => false);//_service.AutodiscoverUrl("mail") Both variants fails
var appointment = new Appointment(_service);
appointment.Subject = "Status Meeting";
appointment.Body = "The purpose of this meeting is to discuss status.";
appointment.Start = DateTime.Now.AddHours(1);
appointment.End = appointment.Start.AddHours(2);
appointment.Location = "Conf Room";
appointment.RequiredAttendees.Add("mail1");
appointment.Save(SendInvitationsMode.SendToNone);
As result I have:
HTTP/1.1 502 Fiddler - Connection Failed
[Fiddler] The connection to 'autodiscover.domain.com' failed.
Error: ConnectionRefused (0x274d). System.Net.Sockets.SocketException
No connection could be made because the target machine actively refused it 157.56.248.169:443
In DNS management I have the following:
Initial domain: This domain is included with your account. It’s set up automatically for you, and you can’t delete it.
If you want to find out why Autodiscover is failing, I would recommend enabling tracing with all of the Autodiscover-related trace tags. Of course I'm assuming that the value "mail" that you're passing there is actually the user's email address.
I am very new to bitcoin and this is my first experiment with bitcoind.
We have been trying to develop an Java based application on BTC using bitcoind (using testnet). We are using simple HTTP Post using Jersey client with basic authentication like given below. We already have jersey client as part of project dependencies. We are running on Mac OS. The bitcoind and java client are hosted in the same system.
Client client = Client.create();
String url = "http://"+username+':'+password+"#localhost:18333";
//String url = "http://localhost:18333";
System.out.println("URL is : "+url);
WebResource webResource = client.resource(url);
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (username, password.toCharArray());
}
});
String input = "{\"method\":\"getblockcount\",\"params\":[],\"id\":\"1\"}";
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
When we execute this, we are getting
Caused by: java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:772)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:769)
From the exception what I understand is, there are some server side errors but i am not able to see errors in the log files. The degug.log does not give any details.
The entries in the bitcoin.conf file is as follows:
rpcuser=bitcoinrpc
rpcpassword=5UKQTzWTf7EEJnkShZhr9tbjpDVNmLMgQkFfWsnZhLey
testnet=1
server=1
Also I tried integrating with bitcoind using json-rpc client as well which resulted in the same error.
Really appreciate any help in resolving this error. Thank you in advance. Let me know if you need any further details.
Regards,
Manjunath
====== EDIT ======
When I inspect the request and response, its giving "Remote server closed the connection before sending response header" error as part of HTTP failure scenario. Following is the request data content :
URL : http://192.168.2.111:18333/
Request Data:
{
"method": "getblockcount",
"params": [],
"id": "1"
}
Please help me in understanding where the mistake is.
================ EDIT =================
Added below entries to bitcoin.conf to allow connections from client. But still facing the same error:
rpcallowip=192.168.2.111
rpcallowip=127.0.0.1
Regards,
Manjunath
After all tweaking, I am able to get it working properly. For the benefit of others, here is the Java Code for making JSON-RPC calls to bitcoind (Using Jersey Client):
bitcoin.conf entries :
rpcuser=bitcoinrpc
rpcpassword=5UKQTzWTf7EEJnkShZhr9tbjpDVNmLMgQkFfWsnZhLey
testnet=1
server=1
#txindex=1
rpcallowip=192.168.2.*
rpcallowip=127.0.0.1
rpcport=8999
#rpctimeout=60000
Make sure you change the port number and dont forget to provide rpcallowip entry pointing to respective IP address.
Client Code:
DefaultClientConfig config = new DefaultClientConfig();
config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,
Boolean.TRUE);
Client client = Client.create(config);
client.addFilter(new HTTPBasicAuthFilter(username, password));
WebResource webResource = client.resource(url);
String input = "{\"id\":\"jsonrpc\",\"method\":\"listaccounts\",\"params\":[]}";
ClientResponse response = webResource.accept("application/json").type("application/json")
.post(ClientResponse.class, input);
Thats it. Your good to start with bitcoind integration.
Regards,
Manjunath