Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up email settings in appsettings web.config

Setting up email details in web.config - but no email is being sent!

  <appSettings>
    <add key="webpages:Version" value="1.0.0.0" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="smtpServer" value="smtp.live.com" />
    <add key="EnableSsl" value = "true"/>
    <add key="smtpPort" value="587" />
    <add key="smtpUser" value="[email protected]" />
    <add key="smtpPass" value="mypasswordgoeshere" />
    <add key="adminEmail" value="[email protected]" />
  </appSettings>

I am using the following class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net;
using System.Configuration;

namespace MVCcars.Utils
{
  public static class MailClient
  {
    private static readonly SmtpClient Client;
    static MailClient()
    {
      Client = new SmtpClient
      {
        Host =
          ConfigurationManager.AppSettings["SmtpServer"],
        Port =
          Convert.ToInt32(
            ConfigurationManager.AppSettings["SmtpPort"]),
        DeliveryMethod = SmtpDeliveryMethod.Network

      };
      Client.UseDefaultCredentials = false;
      Client.Credentials = new NetworkCredential(
      ConfigurationManager.AppSettings["SmtpUser"],
      ConfigurationManager.AppSettings["SmtpPass"]);
    }


    private static bool SendMessage(string from, string to,
      string subject, string body)
    {
      MailMessage mm = null;
      bool isSent = false;
      try
      {
        // Create our message
        mm = new MailMessage(from, to, subject, body);
        mm.DeliveryNotificationOptions =
        DeliveryNotificationOptions.OnFailure;
        // Send it
        Client.Send(mm);
        isSent = true;
      }
      // Catch any errors, these should be logged and
      // dealt with later
      catch (Exception ex)
      {
        // If you wish to log email errors,
        // add it here...
        var exMsg = ex.Message;
      }
      finally
      {
        mm.Dispose();
      }
      return isSent;
    }


    public static bool SendWelcome(string email)
    {
      string body = "Put welcome email content here...";
      return SendMessage(
        ConfigurationManager.AppSettings["adminEmail"],
          email, "Welcome message", body);
    }
  }
}

This is the Account controller:

[HttpPost]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        MembershipCreateStatus createStatus;
        Membership.CreateUser(model.UserName,
          model.Password, model.Email, null, null,
          true, null, out createStatus);
        if (createStatus ==
            MembershipCreateStatus.Success)
        {
          // Send welcome email
          MailClient.SendWelcome(model.Email);
          FormsAuthentication.SetAuthCookie(
            model.UserName,
            false /* createPersistentCookie */);
          return RedirectToAction("create", "Customer");
        }
        else
        {
          ModelState.AddModelError("",
            ErrorCodeToString(createStatus));
        }
    }
    // If we got this far, something failed,
    // redisplay form
    return View(model);   
}

Are the app settings in the web.config right for the enableSsl? any advice welcome

like image 746
Daza Aza Avatar asked Apr 05 '12 04:04

Daza Aza


2 Answers

An even easier way to work with the SmtpClient in .NET is to use the system.net configuration settings. This will allow you to set the defaults for any SmtpClient that is created without having to write code to set all of the properties. This way you can easily modify the entire setup without changing any code.

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

And then in code

 System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
 smtp.Send(mailMessage);

EDIT Here's the orginal code I posted below:

static MailClient() 
{ 
     Client = new SmtpClient 
     { 
         Host = ConfigurationManager.AppSettings["SmtpServer"], 
         Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]), 
         DeliveryMethod = SmtpDeliveryMethod.Network,
         EnableSsl = bool.Parse(ConfigurationManager.AppSettings["EnableSsl"])

     };
  .....
 } 
like image 60
Nick Bork Avatar answered Oct 08 '22 19:10

Nick Bork


In addition to Nick Bork's answer above you may need to make some changes to your asp page and use the

MailSettingsGroup

. Hope this link is helpful How to use the Not-so-new MailSettingsSectionGroup

like image 32
user1270384 Avatar answered Oct 08 '22 19:10

user1270384