Neo
Neo

Reputation: 16239

asp.net mvc send email error: unable to send an email

I have mvc web app sending an email when new user gets created with following code:

private static void SendMail(User user)
        {
            string ActivationLink = "http://localhost/Account/Activate/" +
                                     user.UserName + "/" + user.NewEmailKey;

            var message = new MailMessage("[email protected]", user.Email)
            {
                Subject = "Activate your account",
                Body = ActivationLink
            };

            var client = new SmtpClient("localhost");
            client.UseDefaultCredentials = false;
            client.Send(message);
        }

What's wrong with my code please tell me.

ERROR : Failure sending mail. {"Unable to connect to the remote server"}

Smtp configuration : enter image description here

Upvotes: 0

Views: 1668

Answers (2)

Manas
Manas

Reputation: 2542

Gmail opens in port 587, and u need to enable ssl.

Try following code.

        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(<fromAddress>, <fromPassword>)
        };
        using (var message = new MailMessage(<fromAddress>, <toAddress>)
        {
            Subject = <subject>,
            Body = <body>
        })
        {
            smtp.Send(message);
        }

Upvotes: 1

Fenton
Fenton

Reputation: 251232

Here are the likely causes of this error:

1 You are not supplying the correct authentication details

2 The port is blocked, for example by a firewall

In your example, I notice you are not specifying the port when you create your SmtpClient - it may help to specify it.

Upvotes: 1

Related Questions