通过控制器发送邮件(使用Gmail)

时间:2016-01-27 20:33:10

标签: asp.net-mvc-5 smtpclient

所以,第一次尝试从mvc应用程序发送邮件时,看哪,它不起作用:(

这是我从一些消息来源到目前为止的意大利面条,不用说我最终在错误视图中:

[HttpPost]
public ActionResult Contact(Contact c)
{
    if (ModelState.IsValid)
    {
        try
        {
            MailMessage msg = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            MailAddress from = new MailAddress(c.Email.ToString());
            StringBuilder sb = new StringBuilder();

            msg.To.Add("myaddress@mail.com");
            msg.Subject = "New Message";
            msg.IsBodyHtml = false;
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.EnableSsl = true;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.Credentials = new System.Net.NetworkCredential("myaddress@mail.com", "mypassword");

            sb.Append("Name: " + c.Name);
            sb.Append(Environment.NewLine);
            sb.Append("Email: " + c.Email);
            sb.Append(Environment.NewLine);
            sb.Append("Message: " + c.Message);

            msg.Body = sb.ToString();
            smtp.Send(msg);
            msg.Dispose();

            return View();
        }
        catch (Exception)
        {
                return View("Error");
        }
    }
    return View();
}

0 个答案:

没有答案