C# 如何从 Asp.net Mvc-3 发送电子邮件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9629647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send email from Asp.net Mvc-3?
提问by Dip
How to send a mail through mvc-3 asp.net using c#?
如何使用 c# 通过 mvc-3 asp.net 发送邮件?
I have to send a forgot password so how can I do this? My code is below.
我必须发送一个忘记的密码,我该怎么做?我的代码如下。
Model code..
型号代码..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace TelerikLogin.Models.ViewModels
{
public class ForgotPassword
{
public int user_id { get; set; }
public string user_login_name { get; set; }
public string user_password { get; set; }
[Required]
[Display(Name="Email Address : ")]
public string user_email_address { get; set; }
}
}
Controller code..
控制器代码..
public ActionResult ForgotPassword()
{
return View();
}
[HttpPost]
public ActionResult ForgotPassword(string user_email_address)
{
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\MVC3\TelerikLogin\TelerikLogin\App_Data\Login.mdf;Integrated Security=True;User Instance=True");
DataTable dt1 = new DataTable();
string strQuery = string.Format("SELECT user_password FROM [user_master] WHERE user_email_address='{0}'",user_email_address);
conn.Open();
SqlDataAdapter da1 = new SqlDataAdapter(strQuery, conn);
da1.Fill(dt1);
conn.Close();
if (dt1.Rows.Count > 0)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("[email protected]");
msg.To.Add(user_email_address);
msg.Subject = "Password";
msg.Body = "Test1";
msg.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("[email protected]", "dip", "smtp.gmail.com");
client.Host = "smtp.gmail.com";
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.UseDefaultCredentials = true;
client.Send(msg);
return RedirectToAction("About", "Home");
}
return View();
}
Here I fetched the password of user from database through entered email address..
在这里,我通过输入的电子邮件地址从数据库中获取用户的密码。
View code..
查看代码..
<% using (Html.BeginForm("ForgotPassword", "Account", FormMethod.Post))
{ %>
<%: Html.LabelFor(m => m.user_email_address) %>
<%: Html.TextBox("user_email_address")%>
<%: Html.ValidationSummary(true) %>
<input type="submit" value="Submit"/>
<%} %>
It gives me an error on these line
它在这些行上给了我一个错误
client.Send(msg);
Error messege is:
错误信息是:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. x1sm1264662igc.16
How to solve it? thanks in advance
如何解决?提前致谢
采纳答案by Dmitry S.
Import the System.Net.Mailnamespace.
导入System.Net.Mail命名空间。
The code will look similar to this:
代码将类似于以下内容:
MailMessage mail = new MailMessage();
SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
smtpServer.Credentials = new System.Net.NetworkCredential("userName", "password");
smtpServer.Port = 587; // Gmail works on this port
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Password recovery";
mail.Body = "Recovering the password";
smtpServer.Send(mail);
P.S. You have a SQL injection vulnerability in the sample code. Use a SqlCommandobject with parameters instead of String.Format().
PS 你在示例代码中有一个 SQL 注入漏洞。使用SqlCommand带参数的对象而不是String.Format().
Using SqlDataReaderwould be a lot more efficient to check for a record instead of populating a DataSet.
使用SqlDataReader检查记录而不是填充DataSet.
回答by Dhaust
Have a look at MvcMailer
MvcMailer provides you with an ActionMailer style email sending NuGet Package for ASP.NET MVC 3/4. So, you can produce professional looking emails composed of your MVC master pages and views with ViewBag.
MvcMailer 为您提供 ActionMailer 样式的电子邮件,用于发送 ASP.NET MVC 3/4 的 NuGet 包。因此,您可以使用 ViewBag 生成由 MVC 母版页和视图组成的具有专业外观的电子邮件。
回答by ankit rajput
Use code from following Link to Send Email in mvc3:
使用以下链接中的代码在 mvc3 中发送电子邮件:
回答by Syed Salman Raza Zaidi
i am using this for sending email, in ASP.net MVC3
我在 ASP.net MVC3 中使用它发送电子邮件
System.Web.Helpers.WebMail.SmtpServer = smtp_server;
System.Web.Helpers.WebMail.SmtpPort = smtp_port;
System.Web.Helpers.WebMail.EnableSsl = true;
System.Web.Helpers.WebMail.From = "fromaddress";
StringBuilder sb = new StringBuilder();
sb.Append("<table><tr><td>");
sb.Append(msg);
sb.Append("</td></tr></table>");
string body = sb.ToString();
string To = toemail;
System.Web.Helpers.WebMail.Send(To,subject, body);
回答by Peter Monks
It look like you are trying to send emails through GMail's SMTP service, which this SO question already covers: Sending email in .NET through Gmail
看起来您正在尝试通过 GMail 的 SMTP 服务发送电子邮件,这个问题已经涵盖:通过 Gmail 在 .NET 中发送电子邮件
The only thing that looks missing in your code is that you've set client.UseDefaultCredentials = true, I think you want to set this to falseand provide your own credentials. I've never tried using GMail to send through emails, but I'm guessing you'll need to use a GMail account as your credentials in order to authenticate properly.
您的代码中唯一看起来缺少的是您已设置client.UseDefaultCredentials = true,我认为您想将其设置为false并提供您自己的凭据。我从未尝试过使用 GMail 发送电子邮件,但我猜您需要使用 GMail 帐户作为凭据才能正确进行身份验证。
回答by Arslan Sunny
You should turn on the SMTP service in Window 7 :
您应该在 Window 7 中打开 SMTP 服务:
- go to Control Panel > Programs
- click "Turn window features ON or OFF"
- click Internet Information Service and click OK
- 转到控制面板 > 程序
- 单击“打开或关闭窗口功能”
- 单击 Internet 信息服务,然后单击确定
回答by Yasser Shaikh
you can use this...
你可以用这个...
public void SendEmail(string address, string subject, string message)
{
string email = "[email protected]";
string password = "put-your-GMAIL-password-here";
var loginInfo = new NetworkCredential(email, password);
var msg = new MailMessage();
var smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress(address));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}
回答by Pham
when use smtp for gmail, remember put
使用 smtp 进行 gmail 时,请记住放置
smtpClient.UseDefaultCredentials = false;
smtpClient.UseDefaultCredentials = false;
before
前
smtpClient.Credentials = loginInfo;
回答by Sqalo
Using Systems.Net.Mail;
// POST: /Account/Register
//Here's a simple Mail(MVC4)
public async Task<ActionResult> Register(RegisterViewModel model)
{
Mail email= new Mail();
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
email.to = new MailAddress(model.Email);
email.body = "Hello " + model.Firstname + " your account has been created <br/> Username: " + model.UserName + " <br/>Password: " + model.Password.ToString() + " <br/> change it on first loggin";
ViewBag.Feed = email.reg();
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//Business Logic(this Is you Email Class)
Using Systems.Net.Mail;
public class Mail
{
public MailAddress to { get; set; }
public MailAddress from { get; set; }
public string sub { get; set; }
public string body { get; set; }
public string reg()
{
string feed = "Registration Successful";
var m = new System.Net.Mail.MailMessage()
{
Subject = "",
Body = body,
IsBodyHtml = true
};
m.From = new MailAddress("[email protected] ", "Administrator");
m.To.Add(to);
SmtpClient smtp = new SmtpClient
{
Host = "pod51014.outlook.com",
//Host = "smtp-mail.outlook.com",
Port = 587,
Credentials = new System.Net.NetworkCredential("[email protected] ", " Dut324232"),
EnableSsl = true
};
try
{
smtp.Send(m);
// feed = "";
}
catch (Exception e)
{
}
return feed;
}
public string fogot()
{
string feedback = "";
var m = new System.Net.Mail.MailMessage()
{
Subject = "Reset Password PIN",
Body = body,
IsBodyHtml = true
};
m.From = new MailAddress("[email protected] ", "Administrator");
m.To.Add(to);
SmtpClient smtp = new SmtpClient
{
Host = "pod51014.outlook.com",
Port = 587,
Credentials = new System.Net.NetworkCredential("[email protected] ", "Dut324232"),
EnableSsl = true
};
try
{
smtp.Send(m);
feedback = "Check your email for PIN";
}
catch (Exception e)
{
feedback = "Message not sent" + e.Message;
}
return feedback;
}
}
}

