Szukaj…


Formularz kontaktowy W Asp MVC

1. Model:

 public class ContactModel
 {
    [Required, Display(Name="Sender Name")]
    public string SenderName { get; set; }
    [Required, Display(Name = "Sender Email"), EmailAddress]
    public string SenderEmail { get; set; }
    [Required]
    public string Message { get; set; }
 }

2. Kontroler:

public class HomeController
{
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Contact(ContectModel model)
    {
        if (ModelState.IsValid)
        {
            var mail = new MailMessage();
            mail.To.Add(new MailAddress(model.SenderEmail));
            mail.Subject = "Your Email Subject";
            mail.Body = string.Format("<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>", model.SenderName, mail.SenderEmail, model.Message);
            mail.IsBodyHtml = true;
            using (var smtp = new SmtpClient())
            {
                await smtp.SendMailAsync(mail);
                return RedirectToAction("SuccessMessage");
            }
        }
        return View(model);
    }

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

}

3. Web.Config:

<system.net>
  <mailSettings>
    <smtp from="[email protected]">
      <network host="smtp-mail.outlook.com" 
               port="587" 
               userName="[email protected]"
               password="password" 
               enableSsl="true" />
    </smtp>
  </mailSettings>
</system.net>

4. Widok:

Contact.cshtml

 @model ContectModel
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <h4>Send your comments.</h4>
        <hr />
        <div class="form-group">
            @Html.LabelFor(m => m.SenderName, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.TextBoxFor(m => m.SenderName, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.SenderName)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.SenderEmail, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.TextBoxFor(m => m.SenderEmail, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.SenderEmail)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.Message, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.TextAreaFor(m => m.Message, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.Message)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" class="btn btn-default" value="Send" />
            </div>
        </div>
    }

SuccessMessage.cshtml

<h2>Your message has been sent</h2>

Wysyłanie wiadomości e-mail z klasy

Ten sposób może być bardzo pomocny, ale niektórzy ludzie (np. Ja) nie znoszą powtarzania kodu i tak jak ty nas pokazujesz, oznacza to, że muszę utworzyć kontroler kontaktu z tym samym kodem na każdym proyect, który mamy, więc Myślę, że to też może być pomocne

To moja klasa, która może znajdować się na DLL lub cokolwiek innego

 public class Emails
    {
        public static void SendHtmlEmail(string receiverEmail, string subject, string body, bool Ssl = false)
        {
            //Those are read it from webconfig or appconfig
            var client = new SmtpClient(ConfigurationManager.AppSettings["MailServer"], Convert.ToInt16

                (ConfigurationManager.AppSettings["MailPort"]))
            {
                Credentials = new NetworkCredential(ConfigurationManager.AppSettings["MailSender"], ConfigurationManager.AppSettings["MailSenderPassword"]),
                EnableSsl = Ssl
            };

            MailMessage message = new MailMessage();
            message.From = new MailAddress(ConfigurationManager.AppSettings["MailSender"]);
            message.To.Add(receiverEmail);
            // message.To.Add("[email protected]");
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = body;
            client.Send(message);
        }

    }

tak jak widzisz, będzie czytać z webconfig, więc musimy go skonfigurować, ta konfiguracja jest dla Gmaila, ale każdy host ma swoją własną konfigurację

 <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="AdminUser" value="[email protected]" />
    <add key="AdminPassWord" value="123456789" />
    <add key="SMTPName" value="smtp.gmail.com" />
    <add key="SMTPPort" value="587" />

  </appSettings>


Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow