用于以mvc4疑点发送电子邮件的C#代码

时间:2013-08-27 07:16:00

标签: c# asp.net-mvc-4 smtp

我正在使用c#在mvc4中创建一个网站。目前我在localhost中测试它。我想发送密码给注册人员发送电子邮件。我使用以下代码。

//模型

 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("paru.mr@gmail.com");
            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。请帮帮我

1 个答案:

答案 0 :(得分:0)

Network Credential是电子邮件发件人的用户名和密码(如公司的noreply@abccompany.com这样的defualt邮件地址)。 因此,在这种情况下使用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("me@gmail.com", "password");
        client.Credentials = nc;

        //send email
        client.Send(message);