簡體   English   中英

如何從Asp.net Mvc-3發送電子郵件?

[英]How to send email from Asp.net Mvc-3?

如何使用c#通過mvc-3 asp.net發送郵件?

我必須發一個忘記的密碼,我該怎么辦? 我的代碼如下。

型號代碼..

 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; }
    }
}

控制器代碼..

  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("abc@gmail.com");
            msg.To.Add(user_email_address);
            msg.Subject = "Password";
            msg.Body = "Test1";
            msg.Priority = MailPriority.High;

            SmtpClient client = new SmtpClient();




            client.Credentials = new NetworkCredential("abc@gmail.com", "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();
        }

在這里,我通過輸入的電子郵件地址從數據庫中獲取用戶的密碼。

查看代碼..

<% 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"/>

   <%} %>

它給了我這條線上的錯誤

 client.Send(msg);

錯誤消息是:

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

怎么解決? 提前致謝

導入System.Net.Mail命名空間。

代碼看起來類似於:

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("myemail@gmail.com");
mail.To.Add("recepient@gmail.com");
mail.Subject = "Password recovery";
mail.Body = "Recovering the password";

smtpServer.Send(mail);

PS您在示例代碼中有一個SQL注入漏洞。 使用帶參數的SqlCommand對象而不是String.Format()

使用SqlDataReader可以更有效地檢查記錄而不是填充DataSet

看看MvcMailer

MvcMailer為您提供ActionMailer樣式的電子郵件,發送NuGet Package for ASP.NET MVC 3/4。 因此,您可以使用ViewBag生成由MVC母版頁和視圖組成的專業外觀電子郵件。

你可以用這個......

    public void SendEmail(string address, string subject, string message)
    {
        string email = "-your-id-@gmail.com";
        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);
    }
    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("Mxolisi@gmail.com  ", "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("Mxolisi@gmail.com ", " 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("Mxolisi@gmail.com ", "Administrator");
            m.To.Add(to);
            SmtpClient smtp = new SmtpClient
            {
                Host = "pod51014.outlook.com",
                Port = 587,
                Credentials = new System.Net.NetworkCredential("Mxolisi@gmail.com ", "Dut324232"),
                EnableSsl = true
            };

            try
            {
                smtp.Send(m);
                feedback = "Check your email for PIN";
            }
            catch (Exception e)
            {
                feedback = "Message not sent" + e.Message;
            }
            return feedback;

        }

    }
}

我在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);

您應該在Window 7中打開SMTP服務:

  • 轉到“控制面板”>“程序”
  • 單擊“打開或關閉窗口功能”
  • 單擊Internet信息服務,然后單擊確定

當使用smtp for gmail時,記得把

smtpClient.UseDefaultCredentials = false;

之前

smtpClient.Credentials = loginInfo;

看起來你正試圖通過GMail的SMTP服務發送電子郵件,這個問題已經涵蓋了這個問題: 通過Gmail發送.NET中的電子郵件

你的代碼中唯一看起來缺少的是你設置了client.UseDefaultCredentials = true ,我想你想把它設置為false並提供你自己的憑據。 我從未嘗試使用GMail通過電子郵件發送,但我猜你需要使用GMail帳戶作為您的憑據才能正確進行身份驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM