我应该提到这只是一个学习项目,并且永远不会在线托管。我在本地运行应用程序。用C#ASP.NET发送电子邮件,并使用从URL传入的参数
我有两个问题发送电子邮件在传递的参数:
- 的主要问题:它不发送。
- 只有在点击发送并重定向到同一页面之后,参数才会在视图中填充表单,但它们显示在URL中。
这里是我的代码:
Mail.cs(型号)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LotManager.Models
{
public class Mail
{
public string From = "[email protected]";
public string To { get; set; }
public string Subject = "Parking Alert";
public string Body { get; set; }
}
}
MailController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using LotManager.Controllers;
namespace LotManager.Controllers
{
public class MailController : Controller
{
//
// GET: /SendMailer/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ViewResult Index(LotManager.Models.Mail _objModelMail)
{
var to = Request.QueryString["To"];
ViewBag.To = to;
var body = Request.QueryString["Body"];
ViewBag.Body = body;
if (ModelState.IsValid)
{
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(_objModelMail.From);
string Body = body;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("mygmailusername", "mypassword"); //My actual account info goes here
smtp.EnableSsl = true;
try
{
smtp.Send(mail);
}
catch (Exception)
{
Console.WriteLine("The email was not sent, because I couldn't get it to work. Oops!");
}
return View("Index", _objModelMail);
}
else
{
return View();
}
}
}
}
Index.cshtml(发送邮件查看)
@model LotManager.Models.Mail
@{
ViewBag.Title = "Send";
}
<h2>Send</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<p>To: </p>
<p>@Html.TextBoxFor(m => m.To, new { @Value = @ViewBag.To })</p>
<p>Body: </p>
<p>@Html.TextBoxFor(m => m.Body, new { @Value = @ViewBag.Body })</p>
<input type="submit" value="Send" />
}
该参数传递到URL中的代码:
@Html.Actionlink("Send Notification", "Index", "Mail", new { To = item.Employee.Email, Body = item.Description }, null)
是否有例外,还是电子邮件没有到达? –
电子邮件只是没有到达。我忘了提及我在本地举办这个活动,因为它只是一个学习项目。 –