Asp.net mvc 如何从MVC5应用程序发送电子邮件

Asp.net mvc 如何从MVC5应用程序发送电子邮件,asp.net-mvc,sendmail,Asp.net Mvc,Sendmail,我有一张客户需要填写的表格。提交表单后,我希望将表单索引视图中的基本信息(名字、姓氏、电话号码等)发送到电子邮件。我目前正在使用GoDaddy作为我的托管站点。这有关系吗,或者我可以直接从MVC应用程序发送电子邮件吗?我的模型、视图、控制器有以下内容。我以前从来没有这样做过,我真的不知道该怎么做 型号: public class Application { public int Id { get; set; } [DisplayName("Marital Status")]

我有一张客户需要填写的表格。提交表单后,我希望将表单索引视图中的基本信息(名字、姓氏、电话号码等)发送到电子邮件。我目前正在使用GoDaddy作为我的托管站点。这有关系吗,或者我可以直接从MVC应用程序发送电子邮件吗?我的模型、视图、控制器有以下内容。我以前从来没有这样做过,我真的不知道该怎么做

型号:

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; }
}
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);
}
控制器:

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


@ActionLink(“名字”,“索引”,新的{sortOrder=ViewBag.NameSortParm})
@ActionLink(“姓氏”,“索引”,新的{sortOrder=ViewBag.NameSortParm})
@ActionLink(“提交日期”,“索引”,new{sortOrder=ViewBag.NameSortParm})
@foreach(模型中的var项目){
@DisplayFor(modelItem=>item.FirstName)
@DisplayFor(modelItem=>item.LastName)
@DisplayFor(modelItem=>item.GetDate)
}

您需要一个SMTP服务器来发送电子邮件。不知道戈达迪是如何工作的,但我相信他们会提供一些东西

要从MVC应用发送电子邮件,您可以在代码或
web.config
中指定SMTP详细信息。我建议在配置文件中使用,因为这意味着更容易更改。对于web.config中的所有内容:

SmtpClient client=new SmtpClient();
否则,请在代码中执行:

SmtpClient client=new SmtpClient("some.server.com");
//If you need to authenticate
client.Credentials=new NetworkCredential("username", "password");
现在您可以创建您的消息:

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!";
最后发送:

client.Send(mailMessage);
web.config
设置示例:

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

您可以试试这个
控制器
业务逻辑
看法

@LabelFor(m=>m.From,新的{@class=“col-md-2控制标签”})
@TextBoxFor(m=>m.From,新的{@class=“form control MakeWidth”})
@LabelFor(m=>m.Subject,新的{@class=“col-md-2控制标签”})
@TextBoxFor(m=>m.Subject,新的{@class=“form control MakeWidth”})
@LabelFor(m=>m.Body,新的{@class=“col-md-2控制标签”})
@text区域(m=>m.Body,新的{@class=“form control MakeWidth”})


网络配置网络配置:

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

控制器:

<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>
[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);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务联系人(EmailFormModel)
{
if(ModelState.IsValid)
{
var body=“电子邮件发件人:{0}({1})

消息:

{2}

”; var message=new MailMessage(); message.To.Add(新邮件地址(“name@gmail.com“”);//替换为有效值 message.Subject=“您的电子邮件主题”; message.Body=string.Format(Body,model.FromName,model.FromEmail,model.message); message.IsBodyHtml=true; 使用(var smtp=new SmtpClient()) { 等待smtp.SendMailAsync(消息); 返回重定向操作(“已发送”); } } 返回视图(模型); }
太好了,我马上给你。我应该把代码和电子邮件放在我的索引(post)操作方法中吗?另外,如何将用户提供的信息从表单绑定到电子邮件?我会尝试将它们保存在它们自己的代码模块中。也许是一个接受用户对象的函数。效果很好!有没有办法从提交到邮件正文的表单中添加内容?这对我很有用。但我想在有人注册时收到注册邮件。有人能告诉我使用ASP.NETMVC和SMTP服务器重新注册的链接吗。目前,你只需要把电子邮件放进去,就可以注册。@Unbreakable First,这是一个非常广泛的问题,即使是关于堆栈溢出的普通帖子,更不用说在对答案的评论中了。第二,没有投票就问我更厚颜无耻!不鼓励只使用代码的答案。请解释一下你的答案!
// 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);
    }
    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);
        }
    }