web-dev-qa-db-fra.com

Comment envoyer un email depuis l'application MVC 5

J'ai un formulaire qu'un client doit remplir. Une fois le formulaire soumis, j'aimerais envoyer les informations de base de la vue Index du formulaire (Prénom, Nom, numéro de téléphone, etc.) à un courrier électronique. J'utilise actuellement GoDaddy pour mon site d'hébergement. Est-ce important ou puis-je envoyer l'e-mail directement à partir de mon application MVC? J'ai le suivant pour mon modèle, vue, contrôleur. Je n'ai jamais fait cela auparavant et je ne sais vraiment pas comment s'y prendre. 

Modèle: 

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

Manette: 

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

Vue

<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>
}
14
dc922

Vous aurez besoin d’un serveur SMTP pour envoyer un courrier électronique. Je ne sais pas du tout comment GoDaddy fonctionne, mais je suis sûr qu'ils fourniront quelque chose.

Pour envoyer des courriels à partir d'une application MVC, vous devez spécifier vos détails SMTP dans le code ou dans le web.config. Je recommande dans le fichier de configuration car cela signifie qu'il est beaucoup plus facile de changer. Avec tout dans le web.config:

SmtpClient client=new SmtpClient();

Sinon, faites le dans le code:

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

Maintenant, vous créez votre message:

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

Enfin envoyez le:

client.Send(mailMessage);

Un exemple pour la configuration de web.config:

<system.net>
    <mailSettings>
        <smtp>
            <network Host="your.smtp.server.com" port="25" />
        </smtp>
     </mailSettings>
</system.net>
27
DavidG

Tu peux essayer ça


Manette

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

Logique d'entreprise

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

}

Vue

    <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

6
Matshili Aluwani

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>

Manette:

[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("[email protected]")); //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);
}
3
Anup Shetty
    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
user9817675
// 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("[email protected]", "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);
    }
0
Jim Kay