Recherche…


Formulaire de contact dans Asp MVC

1. modèle:

 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. contrôleur:

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. Voir:

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>

Envoi de courrier électronique de la classe

Cette façon de faire peut être tellement utile, mais certaines personnes (comme moi) ont des problèmes de répétition de code et, comme vous nous le faites savoir, cela signifie que je dois créer un contrôleur de contact avec le même code sur chaque projet. , Je pense que cela peut être utile aussi

Ceci est ma classe, qui peut être sur une DLL ou autre

 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);
        }

    }

comme vous le voyez, il va lire depuis le webconfig, donc, nous devons le configurer, cette configuration est pour Gmail, mais chaque hôte a sa propre configuration

 <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
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow