Send Email in Asp.Net MVC using System.Net.Mail

Send Email in Asp.Net using System.Net.Mail in .NET library via a SMTP server.

 Asp.Net   
 

Posted: June 2, 2017. | By: mustafa

How can we send an email in Asp.Net MVC application. Let's start by adding email configuration settings in web.config. we are going to use Gmail to send email in this below example.

Now add the following AppSettings in the Web.config

    <add key="Host" value="smtp.gmail.com"/>
    <add key="EnableSsl"  value="true"/>
    <add key="Port" value="587"/>
    <add key="Email" value="xyz@gmail.com"/>
    <add key="Password"  value="password"/>


Add common generic method to send email using namespace System.Net.Mail.

using System.Net.Mail;

public void SendMail(string subject, string msgBody, string toAddress, string AttachedFileName = null)
        {
            var fromAddress = ConfigurationManager.AppSettings["Email"];
            string password = ConfigurationManager.AppSettings["Password"];
            MailAddress mailAdress1 = new MailAddress("admin@mail-domain.com");

            try
            {

                var smtp = new SmtpClient
                {
                    Host = ConfigurationManager.AppSettings["Host"],
                    Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]),
                    EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]),
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress, password),
                    Timeout = 10000
                };

                MailMessage message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = msgBody,
                    IsBodyHtml = true,
                };

                message.CC.Add(mailAdress1);// add cc to email address

                // Add attachment
                if (AttachedFileName != null && AttachedFileName != "")
                {
                    Attachment attachment = new Attachment(AttachedFileName, new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Image.Jpeg));
                    attachment.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;

                    message.Attachments.Add(attachment);
                }
                smtp.Send(message);

            }
            catch (Exception ex)
            {
             logger.Error(ex, ex.Message);

            }
        }


In the above SendMail() method we initialized a MailMessage object with constructor passing from & to email address and set IsBodyHtml property to true. Add email address to message.cc & similarly we can add email address to message.ReplyToList to reply at email address.
           

MailAddress replyMail = new MailAddress("admin@mail-domain.com");
                message.ReplyToList.Add(replyMail);


And also add attachment if there is any using MIME media type. Before that we have initialized SmtpClient object to send message or alternatively we can set default smtp settings in web.config as defined below. Define smtp host name, username, password and other mail settings.

<system.net>
    <mailSettings>
      <smtp from="xyz@gmail.com">
        <network host="smtp.gmail.com" password="password" userName="userName@gmail.com" port="587" enableSsl="true"/>
      </smtp>
    </mailSettings>
  </system.net>


In the contoller add follwing code to create email message. Then initialze class object to send email having parameters subject, message, email and we have also added filename for attachment which is optional.

StringBuilder sb = new StringBuilder();
            sb.Append("This is a text email message.");
            sb.Append(Environment.NewLine);
            sb.Append("First name: " + user.FirstName);
            sb.Append(Environment.NewLine);
            sb.Append("Last name: " + user.LastName);
            sb.Append(Environment.NewLine);
            sb.Append("Email: " + user.Email);
            sb.Append(Environment.NewLine);
            sb.Append("Comments: " + user.Message);
            var emailMessage = sb.ToString();
            var attachedFileName = Server.MapPath("~/images/banner.jpeg");
            Common.Utility utility = new Common.Utility();
            utility.SendMail("Test Email", emailMessage, user.Email, attachedFileName);


Now we can try sending email using above code but you might face issue while sending mail through gmail account for authentication. When you try to send mail from code and you find the error - The SMTP server requires a secure connection or the client was not authenticated. This is because Gmail by default prevents access for your e-mail account from custom applications.

 

Following are the cases:

  1. When the password you entered is wrong
  2. Trying to login from some App
  3. Trying to login from the domain other than your time zone/domain or computer


In my case solution was to open my gmail account and go to security settings https://www.google.com/settings/security/lesssecureapps and enable less secure apps to enable login from all apps.


GmailLesssecureapps.png, Asp.Net, MVC, C#,


related posts

Back to top