Search code examples
c#asp.netsmtpclient

Problem with SmtpClient in ASP.NET web app


I am having an issue with SmtpClient in an ASP.NET web application.

I have a generic function that builds an email message and then sends it. The code is as follows:

public static bool SendMessage( string fromName, string toName, string subject, string body ) {
            var smtpClient = new SmtpClient("server address here")
            {
                Port = 587,
                Credentials = new NetworkCredential("user", "pass"),
                EnableSsl = false,
            };
            var mailMessage = new MailMessage
            {
                From = new MailAddress("sender", "Testing"),
                Subject = subject,
                Body = body
            };
            mailMessage.To.Add ( new MailAddress(toName, "Valued Customer") );

            try {
                smtpClient.Send ( mailMessage );
                return true;
            }
            catch (Exception ex) {
                var error = $"ERROR :{ex.Message}";
                return false;
            }
        }

The problem is, I get the following error when I call it:

Mailbox unavailable. The server response was: <email address being sent to> No such user here

Naturally I removed the value in the < >, but in the original error message it is the email address of the recipient. I almost think the SMTP server believes the recipient has to be a user on the system.

What can I try next? I even hard-coded email addresses in rather than using variables, thinking maybe there was some weird issue with that, but it didn't work.


Solution

  • The error is telling you that the the SMTP server does not have a user with that email address (usually it has to do with security around the FROM address). The SMTP server will not send email if it does not recognize the FROM address.

    Solution, change your FROM. Example:

    var mailMessage = new MailMessage
    {
       From = new MailAddress("tester", "[email protected]"),
       Subject = subject,
       Body = body
    };