我在网络应用程序上工作,我被困在这封电子邮件发送代码之间。我正在联系页面,任何人都可以发送电子邮件,你们都知道。这个代码工作正常,但我不能通过这个错误
正如我所说我正在使用Asp.Net Mvc所以这里是我的POST控制器即时通讯使用gmail帐户,这样它就不会在任何邮件服务之间发生冲突。
public ActionResult sendemail()
{
return View();
}
[HttpPost]
public ActionResult sendemail(string to, string from, string subject, string body, string pwd)
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = true;
client.Credentials = new NetworkCredential("faseehyasin12@gmail.com", pwd);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from);
mail.Subject = subject;
mail.Body = body;
try
{
client.Send(mail);
Response.Write("ok");
return View();
}
catch(Exception e)
{
throw e;
}
}
这是我的观点,我想问我真的需要一个密码来发送电子邮件给这个代码中的某人吗?
并且我的GET控制器是空的,只有编写的代码是返回视图()所以我不打算为此采取ss。我还允许“不太安全的应用程序”,但它仍然给我这个错误。需要帮助
答案 0 :(得分:1)
首先转到https://myaccount.google.com/lesssecureapps并将状态更改为已打开。 然后转到https://accounts.google.com/b/0/displayunlockcaptcha,然后点击继续按钮。
请尝试使用以下代码。
string host = "smtp.gmail.com";
int port = 587;
bool ssl = true;
string fromAddress = "faseehyasin12@gmail.com";
string fromPassword = "your password here";
using (var mail = new MailMessage())
{
string subject = "Test";
string body = "Mail test";
mail.From = new MailAddress(fromAddress);
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
mail.To.Add("mail@domain.com");
using (var smtpServer = new SmtpClient(host,port))
{
smtpServer.UseDefaultCredentials = false;
smtpServer.Credentials = new System.Net.NetworkCredential(fromAddress, fromPassword);
smtpServer.EnableSsl = ssl;
smtpServer.Send(mail);
}
}