[英]Send e-mail in C# ASP.NET with parameters passed in from URL
我應該提到,這只是一個學習項目,永遠不會在線托管。 我正在本地運行該應用程序。
我在發送帶有傳入參數的電子郵件時遇到兩個問題:
這是我的代碼:
Mail.cs(模型)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LotManager.Models
{
public class Mail
{
public string From = "myusername@gmail.com";
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)
惡意用戶可以使用您的頁面使用您的電子郵件帳戶向用戶發送垃圾郵件。 這將很快破壞您的Gmail發件人信譽。 從嚴重受損的發件人聲譽中恢復幾乎是不可能的。
第1期
您使用了錯誤的SMTP端口 。
smtp.gmail.com需要SSL的端口465或TLS的端口587。
第2期
您正在使用鏈接(ActionLink)調用控制器,該鏈接將創建GET請求。 但是,由於[HttpPost]屬性,您的控制器操作將僅針對POST調用。 刪除[HttpPost],或者使用post操作而不是鏈接來調用控制器操作。
該參數也不可用,因為您正在使用[HttpPost]
。 參數在GET中可見,而在POST中不可見。
關於第二個問題,請查看Google文檔: https : //support.google.com/a/answer/176600?hl=zh_CN如果要使用端口25,則需要將服務器更改為smtp-relay.gmail.com
。 否則,將SSL的端口更改為465,將TLS的端口更改為587。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.