I have some code that I am attempting to use to send emails from my ASP.NET MVC 5 website. From what I have read I am doing this the right way and the code is correct
public static Task SendEmailAsync(IEnumerable<string> to,
IEnumerable<string> cc, string body)
{
if (to == null || to.Count() == 0)
return null;
if (String.IsNullOrEmpty(body))
throw new ArgumentNullException("body of the email is empty");
// Send email.
return Task.Factory.StartNew(() =>
{
// Client setup.
using (SmtpClient smtpClient = new SmtpClient("smtp.servername.com", 25)) // Tried 587 too.
{
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = Constants.AdminEmailAddress,
Password = Constants.AdminPwd
};
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
// Mail message.
using (MailMessage mail = new MailMessage())
{
mail.Body = body;
mail.From = new MailAddress(Constants.AdminEmailAddress, "Business Name Here");
foreach (var a in to)
mail.To.Add(new MailAddress(a));
if (cc != null)
foreach (var a in cc)
mail.CC.Add(new MailAddress(a));
smtpClient.Send(mail); // Here I get exception.
}
}
});
}
But on the line marked above I get
System.Net.Mail.SmtpException: 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 NNN.NNN.NNN.NNN:MMM
I understand that this is clearly saying that the client cannot connect, but these are the exact same details that I am using to send email from Microsoft Outlook and that works.
Why can't I connect to the mail server using these credentials, what am I missing?
I am aware that I may have to contact the mail service provider and ask for permissions, but this is my first attempt at this and would like some clarification about what to do. I have looked at mandrillapp.com which provides a mail service, is this a good option, can someone advise?
Thank for your time.
Note, I have read
- How to send email from Asp.net Mvc-3?
- http://www.c-sharpcorner.com/UploadFile/sourabh_mishra1/sending-an-e-mail-using-Asp-Net-mvc/
- send email from MVC 4 ASP.NET app
Update
Following the very helpful suggestions by @Dave Zych below I have removed the SmtpException
but I now have System.Security.Authentication.AuthenticationException
saying "The remote certificate is invalid according to the validation procedure.". So I am in the same boat and still cannot send email.