带有电子邮件的 MVC 联系表
[英] MVC Contact Form with Email
本文介绍了带有电子邮件的 MVC 联系表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有人可以帮忙处理一个 MVC 联系表,在提交时发送电子邮件?我想我已经设置了大多数元素,但由于某种原因,表单似乎正在发送(需要很长时间)然后返回表单并没有收到电子邮件.
MailModels.cs:
命名空间 WebApplication1.Models{公共类邮件模型{公共字符串名称 { 获取;放;}公共字符串电子邮件{获取;放;}公共字符串电话{得到;放;}公共字符串消息 { 获取;放;}}}
Contact.cshtml:
@using (Html.BeginForm("Contact", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @id = "contact-form", role = "form"})){@Html.ValidationSummary()<字段集><div class="form-div-1"><label class="name">@Html.TextBoxFor(m => m.Name, new { @placeholder = "Name *", @type = "text" })标签>
<div class="form-div-2"><label class="email">@Html.TextBoxFor(m => m.Email, new { @placeholder = "Email Address *", @type = "email" })标签>
<div class="form-div-3"><label class="phone notRequired">@Html.TextBoxFor(m => m.Telephone, new { @placeholder = "电话号码", @type = "text" })标签>
<div><label class="message">@Html.TextAreaFor(m => m.Message, new { @placeholder = "Message *" })标签>
<div class="button-wrapper"><input type="submit" value="Send" name="submit" class="button"><input type="reset" value="Reset" name="MFReset" class="button"><span>*必填字段</span>
</fieldset>}
HomeController.cs:
使用系统;使用 System.Collections.Generic;使用 System.Data;使用 System.Data.Entity;使用 System.Linq;使用 System.Net.Mail;使用 System.Web;使用 System.Web.Mvc;使用 System.Web.Mvc.Html;使用 WebApplication1.Models;使用 System.Text;命名空间 WebApplication1.Controllers{公共类 HomeController : 控制器{公共 ActionResult 联系(){ViewBag.Message = "测试表格";返回视图();}[HttpPost]公共 ActionResult 联系人(MailModels e){如果(模型状态.IsValid){StringBuilder message = new StringBuilder();MailAddress from = new MailAddress(e.Email.ToString());message.Append("姓名:" + e.Name + "
");message.Append("Email: " + e.Email + "
");message.Append("电话:" + e.Telephone + "
");message.Append(e.Message);MailMessage 邮件 = new MailMessage();SmtpClient smtp = 新 SmtpClient();smtp.Host = "smtp.mail.yahoo.com";smtp.Port = 465;System.Net.NetworkCredential 凭据 = new System.Net.NetworkCredential("yahooaccount", "yahoopassword");smtp.Credentials = 凭证;smtp.EnableSsl = true;mail.From = from;mail.To.Add("雅虎邮箱地址");mail.Subject = "测试查询来自"+e.Name;mail.Body = message.ToString();smtp.Send(mail);}返回视图();}
用这个把我的头撞在砖墙上,任何帮助将不胜感激:-)
解决方案
发送电子邮件需要时间.它应该是一个线程.将您的代码放在一个函数中.并进行以下更改:
public void SendEmail(string toAddress, string fromAddress,字符串主题,字符串消息){尝试{使用 (var mail = new MailMessage()){const string email = "username@yahoo.com";const string password = "密码!";var loginInfo = new NetworkCredential(email, password);mail.From = new MailAddress(fromAddress);mail.To.Add(new MailAddress(toAddress));mail.Subject = 主题;mail.Body = 消息;mail.IsBodyHtml = true;尝试{使用 (var smtpClient = new SmtpClient("smtp.mail.yahoo.com", 465)){smtpClient.EnableSsl = true;smtpClient.UseDefaultCredentials = false;smtpClient.Credentials = loginInfo;smtpClient.Send(mail);}}最后{//处理客户端邮件处理();}}}catch (SmtpFailedRecipientsException ex){foreach(ex.InnerExceptions 中的 SmtpFailedRecipientException t){var status = t.StatusCode;if (status == SmtpStatusCode.MailboxBusy ||状态 == SmtpStatusCode.MailboxUnavailable){Response.Write("传递失败 - 5 秒后重试.");System.Threading.Thread.Sleep(5000);//重发//smtpClient.Send(message);}别的{Response.Write("无法将消息发送到 {0}",t.FailedRecipient);}}}catch (SmtpException Se){//在这里处理异常Response.Write(Se.ToString());}捕获(异常前){Response.Write(ex.ToString());}}
在控制器中调用该函数:
[HttpPost]公共 ActionResult 联系人(MailModels e){如果(模型状态.IsValid){//准备邮件var toAddress = "someadress@yahoo.co.uk";var fromAddress = e.Email.ToString();var subject = "测试查询来自"+ e.Name;var message = new StringBuilder();message.Append("姓名:" + e.Name + "
");message.Append("Email: " + e.Email + "
");message.Append("电话:" + e.Telephone + "
");message.Append(e.Message);//启动邮件线程var tEmail = new Thread(() =>SendEmail(toAddress, fromAddress, subject, message));tEmail.Start();}返回视图();}
如果您没有收到电子邮件,请检查您的垃圾邮件文件夹
I wonder if someone can please help with a MVC Contact Form which send an Email on submission? I think I have most elements setup, but for some reason the form appear to be sending (takes ages) then just returns back to the form and no email is received.
MailModels.cs:
namespace WebApplication1.Models
{
public class MailModels
{
public string Name { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Message { get; set; }
}
}
Contact.cshtml:
@using (Html.BeginForm("Contact", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @id = "contact-form", role = "form" }))
{
@Html.ValidationSummary()
<fieldset>
<div class="form-div-1">
<label class="name">
@Html.TextBoxFor(m => m.Name, new { @placeholder = "Name *", @type = "text" })
</label>
</div>
<div class="form-div-2">
<label class="email">
@Html.TextBoxFor(m => m.Email, new { @placeholder = "Email Address *", @type = "email" })
</label>
</div>
<div class="form-div-3">
<label class="phone notRequired">
@Html.TextBoxFor(m => m.Telephone, new { @placeholder = "Telephone Number", @type = "text" })
</label>
</div>
<div>
<label class="message">
@Html.TextAreaFor(m => m.Message, new { @placeholder = "Message *" })
</label>
</div>
<div class="button-wrapper">
<input type="submit" value="Send" name="submit" class="button"> <input type="reset" value="Reset" name="MFReset" class="button"><span>* Required Fields</span>
</div>
</fieldset>
}
HomeController.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using WebApplication1.Models;
using System.Text;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Contact()
{
ViewBag.Message = "Test Form";
return View();
}
[HttpPost]
public ActionResult Contact(MailModels e)
{
if (ModelState.IsValid)
{
StringBuilder message = new StringBuilder();
MailAddress from = new MailAddress(e.Email.ToString());
message.Append("Name: " + e.Name + "
");
message.Append("Email: " + e.Email + "
");
message.Append("Telephone: " + e.Telephone + "
");
message.Append(e.Message);
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.mail.yahoo.com";
smtp.Port = 465;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("yahooaccount", "yahoopassword");
smtp.Credentials = credentials;
smtp.EnableSsl = true;
mail.From = from;
mail.To.Add("yahooemailaddress");
mail.Subject = "Test enquiry from "+e.Name;
mail.Body = message.ToString();
smtp.Send(mail);
}
return View();
}
Banging my head against a brickwall with this one, any help would be much appreciated :-)
解决方案
Sending an email will take time. It should be a thread. Put your code in a function. And make the following changes:
public void SendEmail(string toAddress, string fromAddress,
string subject, string message)
{
try
{
using (var mail = new MailMessage())
{
const string email = "username@yahoo.com";
const string password = "password!";
var loginInfo = new NetworkCredential(email, password);
mail.From = new MailAddress(fromAddress);
mail.To.Add(new MailAddress(toAddress));
mail.Subject = subject;
mail.Body = message;
mail.IsBodyHtml = true;
try
{
using (var smtpClient = new SmtpClient(
"smtp.mail.yahoo.com", 465))
{
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(mail);
}
}
finally
{
//dispose the client
mail.Dispose();
}
}
}
catch (SmtpFailedRecipientsException ex)
{
foreach (SmtpFailedRecipientException t in ex.InnerExceptions)
{
var status = t.StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
Response.Write("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
//resend
//smtpClient.Send(message);
}
else
{
Response.Write("Failed to deliver message to {0}",
t.FailedRecipient);
}
}
}
catch (SmtpException Se)
{
// handle exception here
Response.Write(Se.ToString());
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Call that function in your controller:
[HttpPost]
public ActionResult Contact(MailModels e)
{
if (ModelState.IsValid)
{
//prepare email
var toAddress = "someadress@yahoo.co.uk";
var fromAddress = e.Email.ToString();
var subject = "Test enquiry from "+ e.Name;
var message = new StringBuilder();
message.Append("Name: " + e.Name + "
");
message.Append("Email: " + e.Email + "
");
message.Append("Telephone: " + e.Telephone + "
");
message.Append(e.Message);
//start email Thread
var tEmail = new Thread(() =>
SendEmail(toAddress, fromAddress, subject, message));
tEmail.Start();
}
return View();
}
If you dont get email, check your spam folder
这篇关于带有电子邮件的 MVC 联系表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!