11

MVC MailMessage does not send it, no exception thrown

 2 years ago
source link: https://www.codesd.com/item/mvc-mailmessage-does-not-send-it-no-exception-thrown.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

MVC MailMessage does not send it, no exception thrown

advertisements

I am running my site locally, testing the "Contact Us" page functionality. The emails are never coming through on the receiving end, but no expection is being thrown. When the user submits the form, here is the endpoint that gets called (I adapted most of this code from http://www.mikesdotnetting.com/article/268/how-to-send-email-in-asp-net-mvc):

[HttpPost]
public async Task<ActionResult> contact(ContactUsViewModel inputModel)
{
    try
    {
        string body =
            "<h4>Email from <strong>{0}</strong> ({1})</h4>" +
            "<p>Date: {2}</p>" +
            "<p>Phone: {3}</p>" +
            "<p>Message:</p><p style='padding-left: 20px;'>{4}</p>" +
            "<br /><p style='font-size: 10px; color: gray;'>This email was generated by testsite.com</p>";
        string to = ConfigurationManager.AppSettings["ContactUsEmailAddress"];
        MailMessage message = new MailMessage();
        message.To.Add(new MailAddress(to));
        message.From = new MailAddress(inputModel.Email);
        message.Subject = "Message from " + inputModel.Name;
        message.Body = String.Format(body, new string[]
            {
                inputModel.Name, inputModel.Email, DateTime.Now.ToLongDateString(), inputModel.Phone, inputModel.UserMessage
            }
        );
        message.IsBodyHtml = true;

        using (var smtp = new SmtpClient())
        {
            var credential = new NetworkCredential
            {
                UserName = ConfigurationManager.AppSettings["EmailServerUserName"],
                Password = ConfigurationManager.AppSettings["EmailServerPassword"]
            };
            smtp.Credentials = credential;
            smtp.Host = ConfigurationManager.AppSettings["EmailServerHost"];
            smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["EmailServerPort"]);
            smtp.EnableSsl = true;
            await smtp.SendMailAsync(message);
            return View(new ContactUsViewModel(true)); //return to the same page, but with form now emptied.
                                                       //"true" param tells the model/Razor page to show a "Email sent" message
        }
    }
    catch (Exception ex)
    {
        // handle exception
    }
}

Here is my web.config. I haven't made any alterations to the default MVC template web.config, other than adding 5 new keys to the appSettings section, which are used to reference the email info.

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-HomePuttingSolutionsMVC-20160424082834.mdf;Initial Catalog=aspnet-HomePuttingSolutionsMVC-20160424082834;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="ContactUsEmailAddress" value="[email protected]"/><!--Where site-generated emails will be sent to-->
    <add key="EmailServerUserName" value="[email protected]"/>
    <add key="EmailServerPassword" value="password123"/>
    <add key="EmailServerHost" value="smtp-mail.outlook.com"/>
    <add key="EmailServerPort" value="587"/>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
    </httpModules>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

This is my first site and my first time implementing email, so any help would be very much appreciated. Thanks.

EDIT: It probably goes without saying, but on my side, I have real credentials written into the ContactUsEmailAddress, EmailServerUserName, and EmailServerPassword fields of the web.config, not the dummy values I've included here.


Referencing the article that @MRebati shared in his answer, I was able to get this working by switching from the manual appSettings keys in my web.config to the proper system.web > mailSettings > smtp settings.

  <system.net>
    <mailSettings>
      <smtp from="[email protected]">
        <network host="smtp-mail.outlook.com"
                 port="587"
                 userName="[email protected]"
                 password="password123"
                 enableSsl="true" />
      </smtp>
    </mailSettings>
  </system.net>




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK