Search code examples
asp.net-mvcemailhmail-server

MVC Application cannot send mail through local HMailServer


I am building a form in C#, .NET, and MVC. On the back end the form will send its contents over email. For testing, I am using a local install of hMailServer.

Initially I set HMS to run as localhost.localdomain; the SMTP setting for "local host name" is localhost. I attempted to connect to it on port 587, like so:

SmtpClient smtp = new SmtpClient
{
    Host = WebConfigurationManager.AppSettings["emailServer"],
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = true,
    Credentials = networkCredential
};

I have double- and triple-checked that the credentials are the mail server user and password that I set. Here they are, in case this helps:

<add key="emailUser" value="[email protected]"/>
<add key="emailPassword" value="~~~"/>
<add key="emailServer" value="localhost.localdomain"/>

When using localhost.localdomain, sending mail throws an exception, with the outer message: "Failure sending mail", and the inner message: "The remote name could not be resolved: 'localhost.localdomain'."

So I tried using companyname.com. Sending mail throws an exception, with the outer message: "Failure sending mail", and the inner message: "Unable to connect to the remote server."

I expect either my HMS domain config is wrong or my protocol config is wrong. The HMS documentation didn't help me, but I may not have known what to look for.

ETA hMail server status shows zero processed messages in a week, despite all my testing.


Solution

  • Here is how I configured it for development: Created host file entry like following:

    local.myname.com 127.0.0.1

    Once done, I opened command prompt and make sure it is updated. I tested it by following:

    tracert local.myname.com

    It should return 127.0.0.1 if host file entry is updated.

    Next, in hmail, we need to create a new domain: local.myname.com and add an email address with password. so your email address would be something like [email protected].

    Next is, in advance you need to double check the protocols configuration and IP range vs authentication configuration as well.

    In my case I configured to block external incoming and outgoing emails and skipped authentication for internal emails. So basically that;s what you can do in advance - IP range configuration. Then with the development, you just need to make sure all your emails are *@local.myname.com and it should work.

    Also enable logging in hmail to get detailed error that can help solve the problem because hmail's help documentation works directly with their error codes nicely.

    hMail is actually good choice for real emails. For development, I would recommend using smtp4dev though.