2

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

  1. How to send email from Asp.net Mvc-3?
  2. http://www.c-sharpcorner.com/UploadFile/sourabh_mishra1/sending-an-e-mail-using-Asp-Net-mvc/
  3. 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.

Community
  • 1
  • 1
MoonKnight
  • 23,214
  • 40
  • 145
  • 277
  • regarding the remote certificate, has it been added to your computer as as a trusted cert? – user1666620 Dec 08 '14 at 15:39
  • No, I am totally new to this, so I am unaware of the requirement and how to do this. Where would I get the certificate? I am sure once I have the certificate I could establish how to add it... Thanks for your comment. – MoonKnight Dec 08 '14 at 15:42

1 Answers1

3

Don't specify UseDefaultCredentials (or set it to false). That causes it to use the credentials of the currently logged in user, not what you set in the Credentials property.

From MSDN:

Some SMTP servers require that the client be authenticated before the server sends e-mail on its behalf. Set this property to true when this SmtpClient object should, if requested by the server, authenticate using the default credentials of the currently logged on user. For client applications, this is the desired behavior in most scenarios.

...

If the UseDefaultCredentials property is set to false, then the value set in the Credentials property will be used for the credentials when connecting to the server. If the UseDefaultCredentials property is set to false and the Credentials property has not been set, then mail is sent to the server anonymously.

Community
  • 1
  • 1
Dave Zych
  • 21,581
  • 7
  • 51
  • 66
  • Unfortunately that has not helped. Same exception thrown with exactly the same message... – MoonKnight Dec 08 '14 at 15:18
  • @Killercam Did you set it to `false` or delete the line? If you set it to false, try deleting the line, that might actually make it work for reasons I will explain if it works. – Dave Zych Dec 08 '14 at 15:22
  • Okay, that has worked, but now on the same line I have an `System.Security.Authentication.AuthenticationException` saying "The remote certificate is invalid according to the validation procedure.". Now slightly different issue, but still can send mail... – MoonKnight Dec 08 '14 at 15:31
  • I have updated the question slightly to encompass this change. Thanks very much for your time and help, it is most appreciated. – MoonKnight Dec 08 '14 at 15:33
  • The reason removing the line worked is explained here: http://stackoverflow.com/questions/12167381/confused-with-the-smtpclient-usedefaultcredentials-property/14130274#14130274 – Dave Zych Dec 08 '14 at 15:37
  • @Killercam this might help you fix your new error: http://stackoverflow.com/questions/18102321/security-authentication-authenticationexception-the-remote-certificate-is-inval – Dave Zych Dec 08 '14 at 15:42
  • Yeah, brilliant. But one last question. How do I go about getting an SSL Certificate and where do I get it from? – MoonKnight Dec 08 '14 at 15:49
  • You can create a self signed one, or get one from GoDaddy, or Comodo, or DigiCert, or lots of places. That's out of scope here. – Dave Zych Dec 08 '14 at 16:06