我應該提到這只是一個學習項目,並且永遠不會在線託管。我在本地運行應用程序。用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)
是否有例外,還是電子郵件沒有到達? –
電子郵件只是沒有到達。我忘了提及我在本地舉辦這個活動,因爲它只是一個學習項目。 –