Search code examples
c#emailsmtplocalhostmail-server

localhost wont connect to mailserver


public bool send()
{
    try
    {
        string body = _omschrijving;
        var fromAddress = new MailAddress("[email protected]", "userfrom");
        var toAddress = new MailAddress("[email protected]", "userto");

        const string subject = "mailmessage";

        var smtp = new SmtpClient
        {
            Host = an IP address provided by the webhosting company,
              UseDefaultCredentials = false,
              DeliveryMethod = SmtpDeliveryMethod.Network,
              Credentials = new NetworkCredential("[email protected]", "password")
        };

        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            IsBodyHtml = true,
            Body = "naam: " + _naam + "<br />mail: " + _email + "<br />content: " + body
        })
        {
            smtp.Send(message);
        }

        return true;
    }
    catch
    {
        return false;
    }
}

This is the code I use to send mails with a simple form on my website. _omschrijving, _email, _naam are fields from the class the method is in. I also changed information like passwords for security purposes. I tried using this from my localhost and it failed. It could not connect to the server.

I tried publishing my project to the webserver (where the mailserver is also located) and it worked perfectly.

I'm glad it works, but I wonder why it wouldn't connect to the mailserver when debugging on the localhost? Can anyone explain this behaviour?


Solution

  • yes your hoster configured his mail-server to only accept connections from his very own webservers which is also common practice for database-severs