Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send email from MVC 5 application

I have a form that a customer is required to fill out. Once the form is submitted, I'd like to send the basic information from the form's Index view (First Name, Last Name, Phone Number, etc..) to an email. I'm currently using GoDaddy for my hosting site. Does this matter, or can I send the email directly from my MVC application? I have the following for my Model, View, Controller. I've never done this before and am really not sure how to go about it.

Model:

public class Application
{
    public int Id { get; set; }

    [DisplayName("Marital Status")]
    public bool? MaritalStatus { get; set; }


    [Required]
    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [DisplayName("Middle Initial")]
    public string MiddleInitial { get; set; }
     [Required]
    [DisplayName("Last Name")]
    public string LastName { get; set; }
}

Controller:

public ActionResult Index()
{
        return View();
}

// POST: Applications/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "Id,FirstName,MiddleInitial,LastName")] Application application)
{
    ViewBag.SubmitDate = DateTime.Now;

    if (ModelState.IsValid)
    {
        application.GetDate = DateTime.Now;
        db.Applications.Add(application);
        db.SaveChanges();
        return RedirectToAction("Thanks");
    }

    return View(application);
}

View

<table class="table table-striped">
    <tr>
        <th>
           @Html.ActionLink("First Name", "Index", new { sortOrder = ViewBag.NameSortParm })
        </th>

        <th>
            @Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.NameSortParm })
        </th>

        <th>
            @Html.ActionLink("Date Submitted", "Index", new { sortOrder = ViewBag.NameSortParm})
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.GetDate)
        </td>
    </tr>
}
like image 814
dc922 Avatar asked Nov 06 '14 16:11

dc922


People also ask

How do I send an email with an attachment in .NET core?

Credentials – Valid login credentials for the SMTP server (Gmail: email address and password). Port – Port Number of the SMTP server (Gmail: 587). When the Form is submitted, the posted values are captured through the EmailModel class object. All the fetched values are set into an object of the MailMessage class.


2 Answers

You will need an SMTP server to send email from. No idea how GoDaddy works but I'm sure they will provide something.

To send emails from an MVC app you either specify you SMTP details in code or in the web.config. I recommend in the config file as it means it's much easier to change. With everything in the web.config:

SmtpClient client=new SmtpClient();

Otherwise, do it in code:

SmtpClient client=new SmtpClient("some.server.com");
//If you need to authenticate
client.Credentials=new NetworkCredential("username", "password");

Now you create your message:

MailMessage mailMessage = new MailMessage();
mailMessage.From = "[email protected]";
mailMessage.To.Add("[email protected]");
mailMessage.Subject = "Hello There";
mailMessage.Body = "Hello my friend!";

Finally send it:

client.Send(mailMessage);

An example for the web.config set up:

<system.net>
    <mailSettings>
        <smtp>
            <network host="your.smtp.server.com" port="25" />
        </smtp>
     </mailSettings>
</system.net>
like image 144
DavidG Avatar answered Oct 06 '22 18:10

DavidG


You can try this


Controller

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ContactDees(FormCollection form)
    {
        EmailBusiness me = new EmailBusiness();
        //string message = Session["Urgent Message"].ToString();
        string from = form["from"];
        string subj = form["sub"];
        string body = form["body"];
        me.from = new MailAddress(from);
        me.sub = subj;
        me.body = body;
        me.ToAdmin();
        return RedirectToAction("Feedback", "First");}

Business Logic

public class EmailBusiness
{
    public MailAddress to { get; set; }
    public MailAddress from { get; set; }
    public string sub { get; set; }
    public string body { get; set; }
    public string ToAdmin()
    {
        string feedback = "";
        EmailBusiness me = new EmailBusiness();

        var m = new MailMessage()
        {

            Subject = sub,
            Body = body,
            IsBodyHtml = true
        };
        to = new MailAddress("[email protected]", "Administrator");
        m.To.Add(to);
        m.From = new MailAddress(from.ToString());
        m.Sender = to;


        SmtpClient smtp = new SmtpClient
        {
            Host = "pod51014.outlook.com",
            Port = 587,
            Credentials = new NetworkCredential("[email protected]", "Dut930611"),
            EnableSsl = true
        };

        try
        {
            smtp.Send(m);
            feedback = "Message sent to insurance";
        }
        catch (Exception e)
        {
            feedback = "Message not sent retry" + e.Message;
        }
        return feedback;
    }

}

View

    <div class="form-horizontal">
        <div class="form-group">
            @Html.LabelFor(m => m.From, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.TextBoxFor(m => m.From, new { @class = "form-control MakeWidth" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.Subject, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.TextBoxFor(m => m.Subject, new { @class = "form-control MakeWidth" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.Body, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.TextAreaFor(m => m.Body, new { @class = "form-control MakeWidth" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" class="btn btn-primary" value="Send Email" />
            </div>
        </div>
    </div>

Web Config

like image 37
Matshili Aluwani Avatar answered Oct 06 '22 18:10

Matshili Aluwani