17

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>
}
DavidG
  • 113,891
  • 12
  • 217
  • 223
dc922
  • 629
  • 3
  • 14
  • 27

6 Answers6

35

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 = "someone@somewhere.com";
mailMessage.To.Add("someone.else@somewhere-else.com");
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>
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • Cool I'll give this ago. Should I put the code and email message in my Index (post) action method? Also, how to bind the user supplied information from the form to the email? – dc922 Nov 06 '14 at 16:40
  • I'd try to keep them in their own code modules. Perhaps a function that takes the User object. – DavidG Nov 06 '14 at 16:56
  • Works great! Is there a way to add content from the form that was submitted to the body of the email? – dc922 Nov 06 '14 at 17:44
  • It worked for me. But I want to have registration mail when some one signs up.Can someone guide me to any link which uses ASP.Net MVC and SMTP server for resgistration. Currently, one just needs to put the email and can get registered. – Unbreakable Aug 06 '17 at 02:01
  • @Unbreakable First, that's a very broad question to ask, even as a normal post on Stack Overflow, let alone in a comment on an answer. Secondly, asking me without even voting is even more cheeky! – DavidG Aug 06 '17 at 09:03
  • I see. Thanks for your inputs. – Unbreakable Aug 06 '17 at 14:48
7

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("21241112@dut4life.ac.za", "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("21241112@dut4life.ac.za", "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

5

Web Config:

<system.net>
  <mailSettings>
    <smtp from="you@outlook.com">
      <network host="smtp-mail.outlook.com" 
               port="587" 
               userName="you@outlook.com"
               password="password" 
               enableSsl="true" />
    </smtp>
  </mailSettings>
</system.net>

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(EmailFormModel model)
{
    if (ModelState.IsValid)
    {
        var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
        var message = new MailMessage();
        message.To.Add(new MailAddress("name@gmail.com")); //replace with valid value
        message.Subject = "Your email subject";
        message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
        message.IsBodyHtml = true;
        using (var smtp = new SmtpClient())
        {
            await smtp.SendMailAsync(message);
            return RedirectToAction("Sent");
        }
    }
    return View(model);
}
Lewis86
  • 511
  • 6
  • 15
Anup Shetty
  • 571
  • 8
  • 10
1
// This example uses SendGrid SMTP via Microsoft Azure
// The SendGrid userid and password are hidden as environment variables
private async Task configSendGridasyncAsync(IdentityMessage message)
    {
        SmtpClient client = new SmtpClient("smtp.sendgrid.net");
        var password = Environment.GetEnvironmentVariable("SendGridAzurePassword");
        var user = Environment.GetEnvironmentVariable("SendGridAzureUser");
        client.Credentials = new NetworkCredential(user, password);

        var mailMessage = new MailMessage();
        mailMessage.From = new MailAddress("itsme@domain.type", "It's Me"); ;
        mailMessage.To.Add(message.Destination);
        mailMessage.Subject = message.Subject;
        mailMessage.Body = message.Body;
        mailMessage.IsBodyHtml = true;

        await client.SendMailAsync(mailMessage);
        await Task.FromResult(0);
    }
Jim Kay
  • 91
  • 6
0
    public static async Task SendMail(string to, string subject, string body)
    {
        var message = new MailMessage();
        message.To.Add(new MailAddress(to));
        message.From = new MailAddress(WebConfigurationManager.AppSettings["AdminUser"]);
        message.Subject = subject;
        message.Body = body;
        message.IsBodyHtml = true;

        using (var smtp = new SmtpClient())
        {
            var credential = new NetworkCredential
            {
                UserName = WebConfigurationManager.AppSettings["AdminUser"],
                Password = WebConfigurationManager.AppSettings["AdminPassWord"]
            };

            smtp.Credentials = credential;
            smtp.Host = WebConfigurationManager.AppSettings["SMTPName"];
            smtp.Port = int.Parse(WebConfigurationManager.AppSettings["SMTPPort"]);
            smtp.EnableSsl = true;
            await smtp.SendMailAsync(message);
        }
    }
0

Add namspace

using System.Net.Mail;

        try
        {
            if (ModelState.IsValid)
            {
                visitorBAL = new VisitorBAL();
                result = visitorBAL.AddVisitor(visitorModel);
                if (result)
                {
                    string body = body;
                    MailMessage mail = new MailMessage();
                    mail.From = new MailAddress("abc@gmail.com");
                    mail.To.Add(model.Email);
                    mail.Subject = "Sample Detail";
                    mail.Body = body;
                    SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
                    smtp.EnableSsl = true;
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new System.Net.NetworkCredential("abc@gmail.com", "asdda3232d");
                    smtp.Host = "smtp.gmail.com";
                    smtp.Port = 587;
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtp.Send(mail);
                 }
            }
        }
        catch (Exception ex)
        {
           throw;
        }
  • Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? **If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient.** Can you kindly [edit] your answer to offer an explanation? – Jeremy Caney Jul 10 '23 at 01:00