在ASP.NET Core MVC 2.1中将用户消息从我的网站发送到我的电子邮件

时间:2019-01-25 17:48:04

标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.1

我在ASP.NET Core MVC 2.1中具有以下C#代码,以便从我的网站向我发送用户消息:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ContactSohJel(string txtEmail, string txtSubject, string txtFirstName, string txtLastName, string txtMessage)
{
    using (MailMessage message = new MailMessage())
    {
        try
        {
            MailMessage mail = new MailMessage();
            //mail.From = new MailAddress("mail@sohjel.ir");
            mail.To.Add("mail@sohjel.ir");
            mail.CC.Add("sohjelveh@gmail.com");
            mail.Bcc.Add("sohjel@yahoo.com");
            mail.From = new MailAddress(txtEmail, txtSubject, System.Text.Encoding.UTF8);
            mail.Subject = "Subject: " + txtSubject + " --- " + "This Message Has Been Sent From: SohJel Let's Learn English WebSite. Microsoft ASP.NET Core MVC";
            mail.SubjectEncoding = System.Text.Encoding.UTF8;
            mail.Body = "<h1>Sender</h1><br/><h2>Information:<br/></h2><h3><strong>First Name: </strong>" + txtFirstName + "<br/><strong>Last Name: </strong>" + txtLastName + "<br/><strong>Email: </strong>" + txtEmail + "<br/><strong>Subject: </strong>" + txtSubject + "<br/><h2>Message: <br/></h2><h3><textarea rows=15 cols=80>" + txtMessage + "</textarea><br/>" + "<br/>" + "<br/>" + "<br/>" + "</h3>" + "This Message Has Been Sent From: SohJel Let's Learn English WebSite.";
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml = true;
            mail.Priority = MailPriority.High;
            SmtpClient client = new SmtpClient();

            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential("mail@sohjel.ir", "********");
            client.Port = **;
            //client.Port = ***;
            client.Host = "***.***.***.**";
            client.EnableSsl = false;
            await client.SendMailAsync(mail);
            TempData["testmsg"] = " Your Message Sent Successfully To Me! ";
        }
        catch (Exception ex)
        {
            TempData["testmsg"] = " An Error Occured!: Your Message Was NOT Sent To Me! ";
            ViewBag.Title = ex.Message;
        }
    }
    return View("ContactSohJel");
}

现在,我的问题是消息未发送给我! *此代码可在LOCALHOST上与我的gmail帐户一起使用,但在我的网站上不起作用!

1 个答案:

答案 0 :(得分:0)

错误似乎很明显。 “ FROM”地址域必须与身份验证域相同。

您大概是在FROM头中传递用户的电子邮件地址。那不行您应该在FROM字段中使用自己的地址。