[英]Sending an email via contact form with System.Net.Mail Asp.Net MVC C#
[英]Not in sending email via SMTP in contact form in asp.net?
我做了一个联系表格,没有错误,但是没有发送电子邮件,这是我页面的主要目的吗? 我正在使用SMTP gmail发送电子邮件。 密码已隐藏在此代码中,请在尝试之前更改密码。 我很困惑为什么它不起作用。我已经尝试了很多,但都徒劳无功。 我在MVC 5中工作,我认为与此有关。
//Model class code starts...........................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace Contacts.Models
{
public class Contact
{
[Required]
[Display(Name = "Name *")]
public string Name { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address *")]
public string Email { get; set; }
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone Number")]
public string Phone { get; set; }
[Required]
[Display(Name = "Message *")]
public string Body { get; set; }
public DateTime SentDate { get; set; }
public string IP { get; set; }
public string BuildMessage()
{
var message = new StringBuilder();
message.AppendFormat("Date: {0:yyyy-MM-dd hh:mm}\n", SentDate);
message.AppendFormat("Email from: {0}\n", Name);
message.AppendFormat("Email: {0}\n", Email);
message.AppendFormat("Phone: {0}\n", Phone);
message.AppendFormat("IP: {0}\n", IP);
message.AppendFormat("Message: {0}\n", Body);
return message.ToString();
}
}
}
Model class code end .............................
Controller class code starts .............................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Contacts.Models;
using System.Net;
using System.Net.Mail;
using System.Collections;
namespace Contacts.Controllers
{
public class ContactController : Controller
{
public ActionResult Index()
{
ViewBag.Success = false;
return View(new Contact());
}
[HttpPost]
public ActionResult Index(Contact contact)
{
ViewBag.Success = false;
{
try
{
if (ModelState.IsValid)
{
// Collect additional data;
contact.SentDate = DateTime.Now;
contact.IP = Request.UserHostAddress;
SmtpClient smtpClient = new SmtpClient();
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential
("tehmina.diya@gmail.com", "********");
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("tehmina.diya@gmail.com"); // From
mail.To.Add(new MailAddress("tehmina.diya@gmail.com")); // To
mail.Subject = "Your email subject"; // Subject
mail.Body = contact.BuildMessage();
contact.BuildMessage(); // Body
ViewBag.Success = true;
smtpClient.Send(mail);
}
}
catch (Exception e)
{
Response.Write("Success");
}
}
return View();
}
}
}
Controller class code ends .............................
View class code Starts.............................
@model Contacts.Models.Contact
@{
ViewBag.Title = "Contact Page";
}
<h2> Contact Page</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
@Html.ValidationSummary(true, "Sending message was unsuccessful. Please correct the errors and try again.")
@if (ViewBag.Success)
{
<h3>Your message was successfully sent!</h3>
}
@using (Html.BeginForm())
{
<div>
<fieldset>
<legend>Contact Information</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Phone)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Phone)
@Html.ValidationMessageFor(model => model.Phone)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
@Html.ValidationMessageFor(model => model.Body)
<br />
<textarea rows="10" cols="60" name="Body"></textarea>
</div>
<p>
<input type="submit" value="Send" />
</p>
</fieldset>
</div>
}
//View class ends....................
这是处理smtp和gmail的stackoverflow中的重要链接。
无论如何,我让您的代码正常工作。 您的MVC代码中有几个小错误。
在控制器中,在catch块中,
catch (Exception e)
{
Response.Write("Success");
}
更改为
catch (Exception e)
{
ModelState.AddModelError("",e.Message);
}
这会将您从gmail收到的错误添加到模型状态。 catch块会捕获错误,而不是成功!
然后在您看来,您具有以下代码行
@Html.ValidationSummary(true, "Sending message was unsuccessful. Please correct the errors and try again.")
更改为:
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
这将显示错误消息,如果传输失败,您将在catch块中捕获该错误消息。
现在,转到您的控制器并在下一行之前
smtpClient.Send(mail)
并添加以下代码
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Timeout = 20000;
这样看起来像这样
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Timeout = 20000;
smtpClient.Send(mail)
它应该工作。 如果您开始超时,则只需增加代码中的超时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.