Visual Studio 2013 C#网站联系表单邮件发送实现求助
实现C# MVC表单提交并发送邮件到指定邮箱
没问题,我来帮你搞定这个需求!你的现有代码里表单还指向PHP页面,我们需要调整成C# MVC的提交逻辑,同时添加邮件发送的功能,步骤如下:
1. 修正HTML表单的提交目标
首先把你的表单action改成指向Home控制器的POST方法,同时设置method="post":
<form action="@Url.Action("Contacto", "Home")" method="post"> @Html.AntiForgeryToken() <!-- 加上这个防止CSRF攻击,很重要 --> <input type="text" id="fname" name="firstname" placeholder="O seu nome.." required> <input type="text" id="lname" name="lastname" placeholder="O seu último nome.." required> <input type="text" name="email" placeholder="Email" required> <textarea id="subject" name="subject" placeholder="Escreva o seu texto.." style="height:170px" required></textarea> <br /> <input type="submit" value="Enviar"> </form>
2. 在HomeController中添加POST处理方法
我们需要新增一个接收表单数据并发送邮件的方法,记得引用System.Net.Mail命名空间:
using System.Net; using System.Net.Mail; using System.Web.Mvc; namespace SiteTESTE.Controllers { public class HomeController : Controller { // GET: 显示联系表单 public ActionResult Contacto() { return View(); } // POST: 处理表单提交并发送邮件 [HttpPost] [ValidateAntiForgeryToken] // 和表单里的AntiForgeryToken对应 public ActionResult Contacto(string firstname, string lastname, string email, string subject) { if (ModelState.IsValid) { try { // 拼接邮件内容 string emailBody = $"Nome completo: {firstname} {lastname}\n"; emailBody += "---\n"; emailBody += $"Email do remetente: {email}\n"; emailBody += "---\n"; emailBody += $"Mensagem:\n{subject}"; // 创建邮件对象 var mailMessage = new MailMessage { From = new MailAddress(email), // 用用户填写的邮箱作为发件人 Subject = $"Nova mensagem de contacto: {firstname} {lastname}", Body = emailBody, IsBodyHtml = false // 如果需要HTML格式邮件,改成true即可 }; // 添加你的收件邮箱 mailMessage.To.Add("seu-email-aqui@dominio.com"); // 发送邮件(推荐从web.config读取配置,后面会说) using (var smtpClient = new SmtpClient()) { // 如果你不想硬编码配置,可以跳过这段,直接用web.config的配置 smtpClient.Host = "smtp.seu-dominio.com"; // 比如smtp.gmail.com smtpClient.Port = 587; // 对应SMTP端口,Gmail是587 smtpClient.EnableSsl = true; // 开启SSL加密 smtpClient.Credentials = new NetworkCredential("seu-email@dominio.com", "sua-senha"); // 你的邮箱账号密码 smtpClient.Send(mailMessage); // 发送成功后给用户反馈 ViewBag.SuccessMessage = "A sua mensagem foi enviada com sucesso! Entraremos em contacto em breve."; return View(); } } catch (Exception ex) { // 捕获错误并提示用户 ViewBag.ErrorMessage = $"Ocorreu um erro ao enviar a mensagem: {ex.Message}"; return View(); } } // 如果表单验证失败,返回原页面 return View(); } } }
3. 推荐:把SMTP配置放到web.config
硬编码邮箱账号密码不安全,也不方便修改,我们可以把配置写到web.config里,在<configuration>节点下添加:
<system.net> <mailSettings> <smtp from="seu-email@dominio.com"> <network host="smtp.seu-dominio.com" port="587" enableSsl="true" userName="seu-email@dominio.com" password="sua-senha" /> </smtp> </mailSettings> </system.net>
这样控制器里的SmtpClient代码可以简化成:
using (var smtpClient = new SmtpClient()) { smtpClient.Send(mailMessage); ViewBag.SuccessMessage = "A sua mensagem foi enviada com sucesso! Entraremos em contacto em breve."; return View(); }
4. 在视图中添加反馈信息显示
在表单下方添加代码,让用户能看到发送结果:
@if (!string.IsNullOrEmpty(ViewBag.SuccessMessage)) { <div style="color: green; margin-top: 15px;">@ViewBag.SuccessMessage</div> } @if (!string.IsNullOrEmpty(ViewBag.ErrorMessage)) { <div style="color: red; margin-top: 15px;">@ViewBag.ErrorMessage</div> }
注意事项
- 如果使用Gmail作为发件邮箱,现在需要创建应用专用密码(因为普通密码会被Google的安全策略拦截),或者暂时允许“不太安全的应用访问”(不推荐)。
- 确认你的服务器允许出站SMTP连接,部分主机商会限制25端口,建议使用587或465端口。
- 测试时可以先在本地运行,确保SMTP配置正确,再部署到服务器。
内容的提问来源于stack exchange,提问作者jonysniper
相关产品推荐
相关产品推荐

