Ricerca…


Modulo di contatto in Asp MVC

1. Modello:

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

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

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>

Invio di email da una classe

In questo modo può essere così utile, ma alcune persone (come me) sono a rischio di codice ripetuto e, come ci mostri, significa che ho bisogno di creare un controller di contatto con lo stesso codice su ogni progetto che abbiamo, quindi , I cosa che questo può essere utile anche

Questa è la mia classe, che può essere su una DLL o qualsiasi altra cosa

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

    }

come vedi che leggerà da webconfig, quindi, abbiamo bisogno di configurarlo, questa configurazione è per Gmail, ma ogni host ha la propria configurazione

 <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
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow