如何从MVC 4 .net中的控制器发送电子邮件?

时间:2016-08-26 06:39:58

标签: asp.net-mvc email asp.net-mvc-4 smtp

如果我在本地系统的IIS中托管网站,我有以下代码可以正常工作。但是如果我在我的Windows Server上托管该网站,它就不会发送邮件。

控制器代码:

[HttpPost]
public ActionResult Index()
{
    string tomail = "test@godaddyserver.com";
    string SMTPServer = "smtpout.secureserver.net";
    string SMTPUserName = "test@godaddyserver.com";
    string SMTPPassword = "test123456";
    string strMailTitle = "Inquiry Mail";
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient(SMTPServer);
    SmtpServer.Credentials = new NetworkCredential(SMTPUserName, SMTPPassword);
    mail.From = new MailAddress(tomail, strMailTitle);
    SmtpServer.Port = 25;
    mail.To.Add(tomail);
    mail.Subject = "Inquiry Mail";
    mail.IsBodyHtml = true;

    string mailTemplatePath = Server.MapPath("~/template/AdminContactUs.html");
    StringBuilder MyStringBuilder = new StringBuilder();

    if (System.IO.File.Exists(mailTemplatePath))
        MyStringBuilder.Append(System.IO.File.ReadAllText(mailTemplatePath));

    mail.Body = MyStringBuilder.ToString();
    try
    {
        SmtpServer.ServicePoint.MaxIdleTime = 1;
        SmtpServer.Send(mail);
    }
    catch (Exception e)
    {

    }
}

我忘记添加的一件事是它可以正常使用Exchange Server电子邮件(test@mydomain.com)和SMTP(smtp1.mydomain.com)。目前的电子邮件和SMTP是Godaddy。但是,它与Godaddy,Hostgator或Gmail无法合作。

如果我遗失任何东西,有人可以建议我吗?

0 个答案:

没有答案