Sergio
Sergio

Reputation: 9917

ASP.NET MVC: How to send an html email using a controller?

What would be the simplest way to send a customised html email using asp.net?

I suppose ideally I would like to send html via email rather than returning it to the browser via a ActionResult, as I normally would. This way I could build the email as a view, supply it with data via a model and then fire it using standard .NET email stuff.

It this feasible / the way to do it?

Thanks,

Upvotes: 9

Views: 15189

Answers (5)

user11501894
user11501894

Reputation: 1

    [HttpPost]
    public ActionResult SendEmail(string Type, string name, int Id, string subject, string message, HttpPostedFileBase uploadFile)
    {


        try
        {

            if (ModelState.IsValid)
            {
                var abc = _salesInvoiceMasterService.GetallInvoices().Where(a => a.TransId == Id).FirstOrDefault();

                var xyz = _accountMasterMainService.GetAllData().Where(a => a.Id == abc.CustId).FirstOrDefault();

                var mm = xyz.Email;
                if (mm == null)
                {
                    string isCheckNull = "No";
                    return Json(isCheckNull, JsonRequestBehavior.AllowGet);

                }

                var Sendermail = _systemSettingService.GetSetting().Where(a => a.BranchId == branchId && a.CompanyId == companyId && a.FinancialId == financialYId).FirstOrDefault();
                if (Sendermail.UserName == null)
                {
                    string isCheckNull = "Not";
                    return Json(isCheckNull, JsonRequestBehavior.AllowGet);
                }
                var User = Sendermail.UserName;
                var senderEmail = new MailAddress(Sendermail.UserName.ToString(), "Manabh Software");
                var receiverEmail = new MailAddress(mm, "Receiver");

                var password = Sendermail.Password;
                if (password == null)
                {
                    string isCheckNull = "PassNot";
                    return Json(isCheckNull, JsonRequestBehavior.AllowGet);
                }
                var sub = subject;
                var body = message;
                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = true,
                    Credentials = new NetworkCredential(senderEmail.Address, password.ToString())


                };



                using (MailMessage mail = new MailMessage(senderEmail, receiverEmail))

                {
                    mail.Subject = subject;

                    mail.Body = message;                    

                    System.Net.Mail.Attachment attachment;
                    attachment = new System.Net.Mail.Attachment("D:/Users/Manabh/Downloads/SalesInvoice_" + Type + "_" + name + "_" + Id + ".pdf");

                    mail.Attachments.Add(attachment);

                    smtp.Send(mail);
                }

                return View();


            }
        }
        catch (Exception e)
        {

            string isCheckNull = "NotExist";
            return Json(isCheckNull, JsonRequestBehavior.AllowGet);

        }
        return View();
    }

Upvotes: 0

Ian Mercer
Ian Mercer

Reputation: 39277

This blog post has a good solution for rendering a View to a string so you can send it in email.

/// Static Method to render string - put somewhere of your choosing
public static string RenderPartialToString(string controlName, object viewData)
{
     ViewDataDictionary vd = new ViewDataDictionary(viewData);
     ViewPage vp = new ViewPage { ViewData = vd };
     Control control = vp.LoadControl(controlName);

     vp.Controls.Add(control);

     StringBuilder sb = new StringBuilder();
     using (StringWriter sw = new StringWriter(sb))
     {
         using (HtmlTextWriter tw = new HtmlTextWriter(sw))
         {
             vp.RenderControl(tw);
         }
     }

     return sb.ToString();
}

Upvotes: 10

Hamid
Hamid

Reputation: 1563

You need also to add below codes before sending mail:

mailMessage.IsBodyHtml = true;

Upvotes: -1

Paul Plato
Paul Plato

Reputation: 1501

I use MVC Mailer for all my Email Needs

see the project link below for more information

https://github.com/smsohan/MvcMailer

Upvotes: 2

tuanvt
tuanvt

Reputation: 717

I think sending email in mvc is just the same as in web form, you just need to set the atribute of the mail message to html enabled then it is food to go. Like this code

MailMessage mm = new MailMessage(emmailFrom,emailTo);
mm.Subject = "Your Subject";
mm.IsBodyHtml = true;
mm.Body = body.ToString();

SmtpClient smtp = new SmtpClient();
smtp.Send(mm);

Upvotes: 6

Related Questions