thatthing
thatthing

Reputation: 676

How to include form content in email in MVC

I am sending email upon form submit. How can i include the form content in the email body section?

I am saving form content into mydb with db.Employee.Add(employee); I specify my email text with string text.

Below you can see the code and my form.

namespace MvcApplication8.Controllers
{
public class PTFController : Controller
{
    private UsersContext db = new UsersContext();

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Employee employee)
    {
        if (ModelState.IsValid)
        {
            db.Employee.Add(employee);
            db.SaveChanges();

            string Text = "<html> <head> </head>" +
    " <body style= \" font-size:12px; font-family: Arial\">" +
    ????? +
    "</body></html>";

            SendEmail("[email protected]", Text);

            return RedirectToAction("Index");
        }

        return View(employee);
    }

    public static bool SendEmail(string SentTo, string Text)
    {
        MailMessage msg = new MailMessage();

        msg.From = new MailAddress("[email protected]");
        msg.To.Add(SentTo);
        msg.Subject = "New email";
        msg.Body = Text;
        msg.IsBodyHtml = true;

        SmtpClient client = new SmtpClient("mysmtp.address.com", 25);



        client.UseDefaultCredentials = false;
        client.EnableSsl = false;
        client.Credentials = new NetworkCredential("mywindowsusername", "mypassword");
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        //client.EnableSsl = true;

        try
        {
            client.Send(msg);
        }
        catch (Exception)
        {
            return false;
        }
        return true;
    }
    }
    }

this is the form:

    <h2>Create</h2>

    @using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
    <legend>Employee</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.EmployeeName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.EmployeeName)
        @Html.ValidationMessageFor(model => model.EmployeeName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.DepartmentID)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.DepartmentID)
        @Html.ValidationMessageFor(model => model.DepartmentID)
    </div>

Upvotes: 0

Views: 1442

Answers (1)

andybn
andybn

Reputation: 56

There are some libraries for using Razor Engine (even separated from MVC) as Email templating system. You could use a Razor template to serve as a email body. This is already discussed on this post : Razor views as email templates

Upvotes: 1

Related Questions