2013-08-27 65 views
0

上午正在使用C#做一個網站mvc4。目前我在localhost測試這個。我想發送密碼來註冊個人電子郵件。我使用下面的代碼。在mvc4發送電子郵件C#代碼懷疑

//模型

public void SendPasswordToMail(string newpwd,string email) 
    { 
     string mailcontent ="Your password is "+ newpwd; 
     string toemail = email.Trim(); 
     try 
     { 
      MailMessage mail = new MailMessage(); 
      SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); 
      mail.From = new MailAddress("[email protected]"); 
      mail.To.Add(toemail); 
      mail.Subject = "Your New Password"; 
      mail.Body = mailcontent; 
      //Attachment attachment = new Attachment(filename); 
      //mail.Attachments.Add(attachment); 
      SmtpServer.Port = 25; 
      SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password"); //is that NetworkCredential 
      SmtpServer.EnableSsl = true; 
      SmtpServer.Send(mail); 

     } 
     catch (Exception e) 
     { 
      throw e; 
     } 
    } 

//控制器

string newpwd; 
    [HttpPost] 
    public ActionResult SendPassword(int Id,string email) 
    { 
     bool IsMember=CheckMember(Id); 
     if (IsMember == true) 
     { 
      newpwd = new Member().RandomPaswordGen(); 
     } 
     .......//here i want to call that model 
     return View(); 
    } 

是模型正確與否。什麼應該是這個模型的返回類型(現在它是無效的,我不知道這是如何調用控制器)。以及如何獲得默認的NetworkCredential。請幫我

回答

0

網絡憑證是用戶名和電子郵件發送者的密碼(如在公司的情況下,defualt郵箱如[email protected])。 因此,在這種情況下使用你的Gmail用戶名和密碼。 您可以使用以下代碼發送電子郵件。

var client = new SmtpClient() 
         { 
          Host = "smtp.gmail.com", 
          Port = 587, 
          EnableSsl = true, 

         }; 
     var from = new MailAddress(Email); 
     var to = new MailAddress(Email); 
     var message = new MailMessage(from, to) { Body = Message, IsBodyHtml = IsBodyHtml }; 

     message.Body += Environment.NewLine + Footer; 
     message.BodyEncoding = System.Text.Encoding.UTF8; 
     message.Subject = Subject; 
     message.SubjectEncoding = System.Text.Encoding.UTF8; 

     var nc = new NetworkCredential("[email protected]", "password"); 
     client.Credentials = nc; 

     //send email 
     client.Send(message);