【问题标题】:How to send email from MVC 5 application如何从 MVC 5 应用程序发送电子邮件
【发布时间】:2014-11-06 16:24:36
【问题描述】:

我有一个客户需要填写的表格。提交表单后,我想将表单索引视图中的基本信息(名字、姓氏、电话号码等)发送到电子邮件。我目前正在使用 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);
}

查看

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

【问题讨论】:

    标签: asp.net-mvc sendmail


    【解决方案1】:

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

    要从 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>
    

    【讨论】:

    • 酷我会先给出这个。我应该将代码和电子邮件信息放在我的索引(发布)操作方法中吗?另外,如何将用户提供的信息从表单绑定到电子邮件?
    • 我会尝试将它们保存在自己的代码模块中。也许是一个接受用户对象的函数。
    • 效果很好!有没有办法从提交到电子邮件正文的表单中添加内容?
    • 它对我有用。但是当有人注册时我想有注册邮件。有人可以指导我到任何使用 ASP.Net MVC 和 SMTP 服务器进行注册的链接。目前,只需输入邮箱即可注册。
    • @Unbreakable 首先,这是一个非常广泛的问题,即使作为 Stack Overflow 上的普通帖子,更不用说对答案的评论了。其次,不投票就问我更厚脸皮!
    【解决方案2】:

    你可以试试这个


    控制器

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

    业务逻辑

    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("21241112@dut4life.ac.za", "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("21241112@dut4life.ac.za", "Dut930611"),
                EnableSsl = true
            };
    
            try
            {
                smtp.Send(m);
                feedback = "Message sent to insurance";
            }
            catch (Exception e)
            {
                feedback = "Message not sent retry" + e.Message;
            }
            return feedback;
        }
    
    }
    

    查看

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

    网页配置

    【讨论】:

      【解决方案3】:

      网络配置:

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

      【讨论】:

        【解决方案4】:
        // 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);
            }
        

        【讨论】:

          【解决方案5】:
              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);
                  }
              }
          

          【讨论】:

          • 不鼓励仅使用代码回答。也请解释一下你的答案!
          猜你喜欢
          • 1970-01-01
          • 2013-03-13
          • 1970-01-01
          • 2010-12-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-08
          • 2020-05-24
          相关资源
          最近更新 更多