I am facing an issue while reading emails from my exchange email account using EWS Microsoft API.
Please help me with a solution if anybody has.
Used below code
public static void Main(string[] args)
{
string UserName = "**";
string Password = "**";
string EXCHANGEMAILURL = # "<Exchange Webservice URL>";
ExchangeService service = new ExchangeService();
service.Timeout = 500000;
service.Credentials = new NetworkCredential(UserName, Password);
service.Url = new Uri(EXCHANGEMAILURL);
try
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType) 3072;
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
FindFoldersResults folderSearchResults = service.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(int.MaxValue));
Folder xChangeSourceFolder = folderSearchResults.Folders.ToList().Find(
f => f.DisplayName.Equals("Inbox", StringComparison.CurrentCultureIgnoreCase));
ItemView itemView = new ItemView(50);
FindItemsResults<Item> findIncomingMails = service.FindItems(xChangeSourceFolder.Id, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false),
new ItemView(50));
Item item = findIncomingMails.First();
EmailMessage messageHTML = (EmailMessage) item;
messageHTML.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments, ItemSchema.Body) {
RequestedBodyType = BodyType.HTML
});
string htmlString = messageHTML.Body.Text.ToString();
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred: " + ex);
}
}
The exception
Unable to connect to the remote server :
A connection attempt failed because the connected party did not properly respond after a period of time,or established connection failed because connected host has failed to respond.
It was working before, but since last 1-2 weeks, it stopped working.
I am trying to show an error message for failed recipients in my asp.net webpage. For some reason the code is not stepping into the SmtpFailedRecipientException:
SmtpClient client = new SmtpClient("smtp.server.com", 25) { Credentials = new NetworkCredential("any#one.com", "123456") };
using (var message = new MailMessage { })
{
message.From = new MailAddress(salesPersonDropDownList.SelectedItem.Text);
message.To.Add(mailToTextBox.Text);
message.CC.Add(mailToCCTextBox.Text);
message.CC.Add(mailToCCTextBox2.Text);
message.CC.Add(mailToCCTextBox3.Text);
message.Subject = mailSubjectTextBox.Text;
message.Body = mailBodyTextBox.Text;
try
{
client.Send(message);
}
catch (SmtpFailedRecipientsException ex)
{
string strSmtpFailedRecipientsException = "test";
}
catch (Exception ex)
{
string strException = "test";
}
}
The code is stepping properly into the the second "catch" but for some reason no into the SmtpFailedRecipientsException. Anyone can tell what I am doing wrong?
Thanks in advance
I found the problem by myself.
The SmtpFailedRecipientsException is for exceptions with two or more failed recipients - and in my case I always had only one failed recipient.
For one failed recipient I had to use the SmtpFailedRecipientException.
I have an application that monitors an Exchange Server mailbox for incoming mail. It works on other systems, but for one of our customers we are getting an error: -ERR Command is not valid in this state.
I don't think it has anything to do with the code itself because we get the same error message when we try logging in using Telnet. The error comes when the User is passed. Just for reference, I have added my login code below.
try
{
tcpClient = new TcpClient(Host, Port);
}
catch (SocketException e) { ... }
String response = "";
try
{
streamReader = GetStreamReader(tcpClient);
response = streamReader.ReadLine();
if (response.StartsWith("+OK"))
{
response = SendReceive("USER ", UserName.Trim() + "#" + Domain.Trim());
if (response.StartsWith("+OK"))
response = SendReceive("PASS ", Password);
}
}
catch (Exception e) { ... }
And the SendReceive method is below:
private String SendReceive(String command, String parameter)
{
String result = null;
try
{
String myCommand = command.ToUpper().Trim() + " " + parameter.Trim() + Environment.NewLine;
byte[] data = System.Text.Encoding.ASCII.GetBytes(myCommand.ToCharArray());
tcpClient.GetStream().Write(data, 0, data.Length);
result = streamReader.ReadLine();
}
catch { } // Not logged in...
return result;
}
Some POP3 servers do not allow the USER command to be used until/unless the connection is using SSL.
In other words, you may need to use the STLS command first (if it is supported), or, failing that, you may be required to use a SASL authentication mechanism.
Check the results of the CAPA command for more information.
Oh, and shameless plug: use MailKit instead of trying to roll your own.
I have a website with an ASP.NET MVC backend running .NET 3.5. On this website, there is a script that sends emails using gmail as the mail service. The script runs and sends mail fine locally on my dev machine, but as soon as I upload it to the live server it fails. The only error message it is giving me at the moment is (since I told it to as you will see further down):
The transport failed to connect to the server.
Here is the code for the mailer script:
using System.Net.Mail;
using System.Web.Mail;
using MailMessage = System.Web.Mail.MailMessage;
namespace MySite.Helpers
{
public class GmailHelper
{
private readonly int _port = 465;
private readonly string _accountName;
private readonly string _password;
public GmailHelper(string accountName, string password)
{
_accountName = accountName;
_password = password;
}
public GmailHelper(string accountName, string password, int port)
{
_accountName = accountName;
_password = password;
_port = port;
}
public void Send(string from, string to, string subject, string body, bool isHtml)
{
Send(from, to, subject, body, isHtml, null);
}
public void Send(string from, string to, string subject, string body, bool isHtml, string[] attachments)
{
var mailMessage = new MailMessage
{
From = from,
To = to,
Subject = subject,
Body = body,
BodyFormat = isHtml ? MailFormat.Html : MailFormat.Text
};
// Add attachments
if (attachments != null)
{
foreach (var t in attachments)
{
mailMessage.Attachments.Add(new Attachment(t));
}
}
// Authenticate
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
// Username for gmail - email#domain.com for email for Google Apps
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _accountName);
// Password for gmail account
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _password);
// Google says to use 465 or 587. I don't get an answer on 587 and 465 works - YMMV
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _port.ToString());
// STARTTLS
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);
// assign outgoing gmail server
SmtpMail.SmtpServer = "smtp.gmail.com";
SmtpMail.Send(mailMessage);
}
}
}
And here is how it is called:
[HttpPost]
public ActionResult Employment(EmploymentModel model, FormCollection collection)
{
if (!ModelState.IsValid)
return View(model);
var results = new EmploymentViewModel();
try
{
results.Position = model.Position;
results.FirstName = model.FirstName;
results.LastName = model.LastName;
results.ContactPhone = model.ContactPhone;
results.OtherPhone = model.OtherPhone;
results.Address = model.Address;
results.Email = model.Email;
results.HsDiploma = model.HsDiploma.ToString();
results.CollegeYears = model.CollegeYears;
results.Skills = model.Skills;
results.Employment = model.Employment;
results.DateSent = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
var gmail = new GmailHelper("noreply#mysite.com", "[*removed*]");
var fromAddress = new MailAddress("noreply#mysite.com", "MySite");
var toAddress = new MailAddress("applications#mysite.com", "MySite Employment");
var subject = string.Format("Employment Application for {0} {1}", model.FirstName, model.LastName);
gmail.Send(fromAddress.Address, toAddress.Address, subject, EmployMailBody(results), false);
}
catch (Exception ex)
{
results.Sent = false;
results.Title = "Oops, our mail drone seems to have malfunctioned!";
results.Message = string.Format("We appologize, {0} {1}, but our email system has encountered an error and your email was not sent.</p>",
results.FirstName, results.LastName);
results.Message += Environment.NewLine + "<p>Please try your request later, or fax your résumé to our Corporate office.";
results.Message += Environment.NewLine + JQueryHelpers.GenerateErrorField(ex.Message);
return View("EmploymentSubmit", results);
}
results.Sent = true;
results.Title = "Thank you for your submission!";
results.Message = string.Format("Thank you for your interest in joining our team, {0} {1}!</p>", results.FirstName, results.LastName);
results.Message += Environment.NewLine + "<p>We have successfully recieved your information and will contact you shortly at the number your have provided.";
return View("EmploymentSubmit", results);
}
I am 99% positive that it was functional before when it was up on the site, but I could be mistaken as it has been a month or so since I have had to update the site.
Are there some additional steps I can take to debug this "better" to track down the underlying issue, or did I botch up my code somewhere accidentally?
Thanks!
EDIT1
So I updated the class to use strictly System.Net.Mail. I successfully sent a message from my dev machine. When I uploaded the site to my server, however, I got a new error message:
Request for the permission of type 'System.Net.Mail.SmtpPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
This site is hosted through godaddy.com, and some after searching around it seems godaddy only allows relaying through their smtp server. It looks like I'll have to change hosting providers to get this working properly.
Thanks!
EDIT2
The reason I moved to gmail from godaddy is originally when I had this script up the email would take anywhere from 15 to 45 minutes to arrive at the destination box. This could have been the deprecated code I was using before, but either way it is now being dispatched and arriving within seconds, as it should be. Here is my GoDaddy helper class, in case it will help someone:
public class GoDaddyHelperNet
{
private readonly int _port = 25;
private readonly MailAddress _accountName;
private readonly string _password;
private readonly string _host = "relay-hosting.secureserver.net";
public GoDaddyHelperNet(MailAddress accountName, string password)
{
_accountName = accountName;
_password = password;
}
public GoDaddyHelperNet(MailAddress accountName, string password, int port)
{
_accountName = accountName;
_password = password;
_port = port;
}
public GoDaddyHelperNet(MailAddress accountName, string password, int port, string host)
{
_accountName = accountName;
_password = password;
_port = port;
_host = host;
}
public void Send(MailAddress to, string subject, string body, bool isHtml)
{
Send(_accountName, to, subject, body, isHtml);
}
public void Send(MailAddress from, MailAddress to, string subject, string body, bool isHtml)
{
var smtp = new SmtpClient
{
Host = _host,
Port = _port,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(from.Address, _password),
Timeout = 15000
};
using (var message = new System.Net.Mail.MailMessage(from.Address, to.Address)
{
Subject = subject,
Body = body,
})
smtp.Send(message);
}
}
there is probably a firewall rule or other network device blocking you. verify that you can telnet to the gmail server from your web server and can send an email.
http://www.wikihow.com/Send-Email-Using-Telnet
if you can't you probably have to talk to your network admin. i have email problems like this on about half of my clients web servers.
Gmail has got lots of restrictions on SMTP relay. No more than 100 total recipients per day, IIRC. Limits on recipients per message as well. Limits on message/attachment size. If you exceed the limits or Gmail has decided that you look like a spam artiste, their SMTP server may well refuse the connection for a day or so.
I am getting the fallowing error when i am trying to connect to the IMAP outlook mail box programatically(i am able to connect the server but not able to login). I am 100% confident that i am using the correct username and password.
loginResponse: aaac NO Login Failed
received failed login response from IMAP server
Failed
Thank you in advance...
In the case of Chilkat component, even if your license key is not valid also you will get same error.
Please look at the
Component.LastErrorText
which will have the detals.
Try
Chilkat.Imap imap = new Chilkat.Imap();
imap.UnlockComponent("LicenseText");
// If your IMAP server needs SSL, set the Ssl property = true
// and set the IMAP port to 993.
// imap.Ssl = true;
// imap.Port = 993;
imap.Connect("IP Address");
// Login to an email account.
bool b = imap.Login("username", "password");
Chilkat.Imap imap = new Chilkat.Imap();
bool success; //string responseString;
// Anything unlocks the component and begins a fully-functional 30-day trial.
success = imap.UnlockComponent("Anything for 30-day trial");
if (success != true)
{
MessageBox.Show(imap.LastErrorText);
return;
}
imap.Port = 993;
imap.Ssl = true;
// Connect to an IMAP server.
success = imap.Connect("servername.na.company.org");
if (success != true)
{
MessageBox.Show(imap.LastErrorText);
return;
}
success = imap.IsConnected() ;
MessageBox.Show("suc"+success);
success = imap.Login("username", "pwd");
if (success != true)
{
MessageBox.Show(imap.LastErrorText);
return;
}
// Select an IMAP mailbox
success = imap.SelectMailbox("firstname.lastname#xxxx.com");
if (success != true)
{
MessageBox.Show(imap.LastErrorText);
return;
}