Free Web Development Online Tutorials, Learn to Code
How to send email in Asp.net mvc web application, email sending in Asp.net

Email sending in Asp.net mvc c#

Let's learn how to send email in asp.net MVC application using C#, below we have provided all details step by step

Asp.net MVC Send email from a form

Here are the steps to create an email sending application in asp.net MVC application using C#.

  1. Create a form in razor view, where user can type their email id, subject line, email body content etc.
  2. Set your all SMTP details like SMTP server, username, password, port, from email id, reply to email id etc. in web config fie, so you can change them any time.
  3. Create an instance of MailMessage class, and send all properties correctly.
  4. Create an instance of SmtpClient class, and execute the send method with MailMessage object
Form in Razor View

First we design a simple form with two fields only, i want you to understand the implementation, you can add other fields later.

The following form will be submitted to "sendemail" method of controller "aspnetmvc".

Email
Message

Step 1: Create a form like above form, You can add all other fields like Subject, CC, BCC etc. now we have removed all those fields, so you can understand the core mail sending functionality

@using (Html.BeginForm("sendmail", FormMethod.Post)) {
<div>
<div>Email</div>
<div>
<input type="text" id="txtEmail" style="font: 18px; padding: 5px; width: 350px;" /> </div> <div>Message</div> <div> <textarea id="txtContent" style="font: 18px; padding: 5px; width: 350px; height: 100px;"></textarea> </div> <div style="text-align: center;"> <input type="submit" value="Send Email" /> </div> </div> }
Model

Now create model class with all properties you need to use in email component, below is the example, you may keep adding more fields like CC, BCC etc.

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

public class ContactModel
{        
    [Required(ErrorMessage = "Fullname Required")]
    [StringLength(50, ErrorMessage = "5 to 50 characters.", MinimumLength = 3)]
    public string FullName { get; set; }

    [Required(ErrorMessage = "Email Required")]
    [EmailAddress(ErrorMessage = "Invalid email")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Message Required")]    
    public string EmailBody { get; set; }   
}
Controller Method

Once the form is submitted, following method will get executed in controller. the method will send email asynchronously.

using System.Threading.Tasks;

public async Task<ActionResult> sendemail()
{
    ContactModel model = new ContactModel();


    return await Task.Run(() => View(model));
}


[HttpPost]
public async Task<ActionResult> sendemail(ContactModel model)
{

    // email sending code will come here

    return await Task.Run(() => View(model));
}

Step 2: Add your SMTP details in web.config file, it will be good if keep configuration details in a separate File, and read the file using configuration framework

<SmtpServer>my-SMTP.serverName.IPAddress</SmtpServer>
<SmtpUserName>smtpUserName@mydomain.com</SmtpUserName>
<SmtpPassword>mySMTPPassword</SmtpPassword>
<SMTPPort>25</SMTPPort>
<DisplayName>WebTrainingRoom.com</DisplayName>
<FromEmail>support@webtrainingroom.com</FromEmail>
<ReplyTo>webtrainingroom@gmail.com</ReplyTo>

Step 3: Now create a utility class with some name, here we have created WTRMail, inside that create a method called SendMail() with two object MailMessage and SmtpClient

public class WTRMail
    {
        MailMessage objMail = new MailMessage(MFrom, MTo, MSubject, MBody);

        //Default setting
        objMail.Priority = MailPriority.Normal;
        objMail.IsBodyHtml = this.IsHtmlBody;
        objMail.ReplyTo = new MailAddress(this.ReplyTo);
    }

Step 4: Read all your SMTP configuration information from web.config or configuration framework object

public class WTRMail            
{

string _SmtpServer= ConfigurationManager.AppSettings["SmtpServer"];
string _SmtpUserName= ConfigurationManager.AppSettings["SmtpUserName"];
string _SmtpPassword= ConfigurationManager.AppSettings["SmtpPassword"];
string _SMTPPort= ConfigurationManager.AppSettings["SMTPPort"];           
           
    private bool SendETMail()
    {
        SmtpClient objSmtp = new SmtpClient();
            
        objSmtp.EnableSsl = false ;
        objSmtp.Host = _SmtpServer;
        objSmtp.Port = _SMTPPort;
        objSmtp.Credentials = new System.Net.NetworkCredential(_SmtpUserName, _SmtpPassword);
        objSmtp.Send(objMail);
    }            

}

In above class we have created a SmtpClient object with all configuration information and then finally executed the objSmtp.Send(objMail) method, this is how you can send email in C# application.

You may be interested to know how to send email with attachment in Asp.net core.

Comment
Name
Email
Website
Subscribe
 

hire remote asp.net developer
Send Email in Asp.Net MVC

Useful Links

ASP.NET MVC Interview Questions Answers

Asp.net SMTP Example
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Asp.net Core Tutorial