使用ASP.NET Core“联系我们”页面 - SMTP服务器问题

时间:2016-09-11 05:18:40

标签: c# asp.net email smtp asp.net-core

我是网络编程新手,正在使用ASP.NET核心创建网站。我正在尝试创建一个标准的“与我联系”页面,用户可以在其中输入姓名,电子邮件,主题和用户名。我正在使用MailKit库发送电子邮件:

public IActionResult SendEmail(Contact contact)
{
    var emailMessage = new MimeMessage();

    emailMessage.From.Add(new MailboxAddress(contact.Name, contact.Email));
    emailMessage.To.Add(new MailboxAddress("myname", "myemail"));
    emailMessage.Subject = contact.Subject;
    emailMessage.Body = new TextPart("plain") { Text = contact.Message };

    using (var client = new SmtpClient())
    {
        client.Connect("smtp-mail.outlook.com", 587); 
        client.Authenticate("myemail", "myemailpassword");
        client.Send(emailMessage);
        client.Disconnect(true);
    }
    return RedirectToAction("Index", "Home");
}

我的问题是每当我发送电子邮件时,SMTP服务器只是用我的SMTP帐户信息替换我的“from”标题。这似乎不仅仅是outlook的情况,而是我尝试过的每个主要SMTP服务器,包括gmail。是否有SMTP服务器不会出现此问题,或者我是否需要找到另一种发送电子邮件的方式?

1 个答案:

答案 0 :(得分:1)

首先,您的代码存在问题

    public IActionResult SendEmail(Contact contact)
    {
        var emailMessage = new MimeMessage();
        emailMessage.From.Add(new MailboxAddress("myname", "mymail@mail.com"));
        emailMessage.To.Add(new MailboxAddress("myname", "mymail@mail.com"));
        emailMessage.Subject = contact.Subject;
        emailMessage.Body = new TextPart("plain") 
        { 
         Text = String.Format("This visitor:{0} with this email:{1} Send this message:{2}", 
         contact.Name, contact.Email, contact.Message) 
        };

        using (var client = new SmtpClient())
        {
            client.Connect("smtp-mail.outlook.com", 587);
            client.Authenticate("myemail", "myemailpassword");
            client.Send(emailMessage);
            client.Disconnect(true);
        }
        return RedirectToAction("Index", "Home");
    }

另请访问以下问题,这可能会对您有所帮助:

How to send an e-mail with C# through Gmail