Sending An E-Mail Using ASP.NET MVC
In this post we will discuss about how mail is sent from ASP.NET MVC application.
MailController.cs :-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
namespace SendMail.Controllers
{
public class MailController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult SendMail()
{
string to_email = "EmailId of the one to whom the mail is to be sent";
var from_email = "EmailId of the one who will send the mail";
var subject = "Testing email sending functionality";
var body = "This is a body of testing email functionality";
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress(from_email);
message.To.Add(new MailAddress(to_email));
message.Subject = subject;
message.IsBodyHtml = true; //to make message body as html
message.Body = body;
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("EmailId of the one who will send the mail", "password of the one who will send the mail");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
smtp.Send(message);
return View("Index");
}
}
}
Note: Enable "Less Secure Apps" for the email-id from which you want to send the mail. follow below link - https://www.google.com/settings/security/lesssecureapps
Comments
Post a Comment