EWS (Exchange Web Service) Getting unAuthorized Error - exchangewebservices

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

Related

Unable to reply messages in yahoo using JAVA MAIL API

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.

The connection to 'autodiscover.domain.com' fails using EWS

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.

Mail exception handling in zend framework 2

I am trying to send an email in zend framework 2 using Mail\Transport\Sendmail().
It is showing a runtime exception on invalid email id.
error message is "Unable to send mail: mail(): SMTP server response: 550 5.1.1 ... User unknown"
Zend\Mail\Exception\RuntimeException
$options = new Mail\Transport\SmtpOptions($config_setting);
// render Email Content
$this->renderer = $this->getServiceLocator()->get('ViewRenderer');
$content = $this->renderer->render($config['mail']['templates']. $messageTemplate, $messageParam);
// make a header as html
$html = new MimePart($content);
$html->type = $config['mail']['content_type'];
$body = new MimeMessage();
$body->setParts(array($html,));
// instance mail
$mail = new Mail\Message();
$mail->setBody($body); // will generate our code html from template.phtml
$mail->setFrom($config['mail']['from_email'],$config['mail']['from_name']);
$mail->setTo($mailTo);
$mail->setSubject($subject);
//$transport = new Mail\Transport\Smtp($options);
$transport = new Mail\Transport\Sendmail();
try{
$response = #$transport->send($mail);
return $response;
}
catch(Zend\Mail\Exception\RuntimeException $ex)
{
$ex->getMessage();
$response = array('error' => 1, 'msg' => $ex->getMessage());
//return $response;
}
i want to ignore this exception message.
You have two transports, one Sendmail and one SMTP. Sendmail is an internal mail server on your pc, which should work fine. SMTP is a protocol to let an (possible external) mail server send emails. You can use your own SMPT server, or connect to e.g. Google or Hotmail for sending mails over SMTP.
You have this in your code:
//$transport = new Mail\Transport\Smtp($options);
$transport = new Mail\Transport\Sendmail();
So you are using in your code the Sendmail transport, but the exception is from SMTP:
Unable to send mail: mail(): SMTP server response: 550 5.1.1 ... User unknown
So it seems to me you are using the SMTP in your code somewhere accidentally. Switch to the Sendmail and it should work fine, or check your question again with the code you posted.

Am getting invalid XML as a response from EWS calls?

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();
}
}

SMTP exception while implementing email feature

I am getting following exception while implementing mail feature for my local machine please help me with this
The SMTP server requires a secure
connection or the client was not
authenticated. The server response
was: 5.7.0 Must issue a STARTTLS
command first. 21sm1768418wfi.5
It's exactly as the message describes.
What ever SMTP server you're trying to connect to, requires you to use SSL for that connection, in addition to supplying a username&password.
SMTP over SSL typically occurs on port 465, however you will need to verify this setting with your mail provider.
So you need to specify the correct port, and specify the UseSSL flag.
Using C# it might look like this:
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.emailserver.com");
mail.From = new MailAddress("your_email_address#yahoo.com");
mail.To.Add("to_address#coolguy.com");
mail.Subject = "Test Mail";
mail.Body = "This is a test message";
SmtpServer.Port = 465;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true; //<--- this will do SSL for you.
SmtpServer.Send(mail);