首页 > 解决方案 > C# MVC 发送邮件问题

问题描述

我是 ASP.NET MVC 的新手。我正在尝试发送电子邮件,因此在浏览了有关该主题的文献后,我想出了以下代码。当我发送电子邮件时,结果是发送失败。请协助。

控制器具有以下代码:

public JsonResult SendMailToClients()
{
        bool result = false;

        result = SendEmail("tmasaiti@gmail.com", "attachment test ", "<p>Hi Flow<br />Whats poppin, the email you have been waiting for is finally here.<br />Regards<br />The Master</p>");

        return Json(result, JsonRequestBehavior.AllowGet);
}

public bool SendEmail(string toEmail, string subject, string emailBody)
{
    try
    {
        string senderEmail = System.Configuration.ConfigurationManager.AppSettings["SenderEmail"].ToString();
        string senderPassword = System.Configuration.ConfigurationManager.AppSettings["SenderPassword"].ToString();

        SmtpClient client = new SmtpClient("smtp.gmail.com", 587)
        {
            EnableSsl = true,
            Timeout = 100000,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(senderEmail, senderPassword)
        };

        MailMessage message = new MailMessage(senderEmail, toEmail, subject, emailBody)
        {
            IsBodyHtml = true,
            BodyEncoding = UTF8Encoding.UTF8
        };

        client.Send(message); 

        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

观点如下:

var SendEmail = function () {
    $.ajax({
        type: "Post",
        url: "/Home/SendMailToClients",
        success: function (data) {
            if (data == true) {
                alert("Message was sent successfully");
            }
            else
            {
                alert("Failure to send Message");
            }
        }
    });
}
@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>ASP.NET</h1>
        <p><a class="btn btn-primary btn-lg" onclick="SendEmail()">Send email now &raquo;</a></p>
</div>

以下错误是我得到的:

System.dll 中的“System.Net.Mail.SmtpException”

标签: c#ajaxasp.net-mvcweb

解决方案


推荐阅读