首页 > 解决方案 > 如何在 asp.net core 中使用 Mailkit 通过“联系我们”表单发送电子邮件

问题描述

大家好!

我在使用联系表发送电子邮件时遇到问题。目标是让用户输入他的电子邮件地址、主题和消息,然后电子邮件就会显示在我的邮箱中。我遇到的问题是电子邮件不是来自用户输入的电子邮件地址,而是来自应该接收消息的地址。基本上我一直给自己发邮件。我向用户发送电子邮件没有问题,例如发票或订单状态...

我试图在调试模式下运行我的应用程序,一切似乎都很好。Post 方法模型具有我输入的值,并且 SendEmail 方法没有用我的地址替换“FROM ADDRESS”。

private string recipientAddress = "myaddress@domain.com"

 public IActionResult Contact(ContactViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View();
        }
        emailSender.SendEmail(recipientAddress, model.Subject, model.EmailBody, model.SenderEmail);
        return RedirectToAction("Index");
    }

public void SendEmail(string recipient, string subject, string emailBody, string emailSender = null)
    {
        string smtpServer = emailConfiguration.SmtpServer;
        int smtpPort = emailConfiguration.SmtpPort;
        string smtpUsername = emailConfiguration.SmtpUsername;
        string smtpPassword = emailConfiguration.SmtpPassword;

        var message = new MimeMessage();
        var fromAddress = string.IsNullOrEmpty(emailSender) ? smtpUsername : emailSender;
        message.To.Add(new MailboxAddress(recipient));
        message.From.Add(new MailboxAddress(fromAddress));
        message.Subject = subject;
        message.Body = new TextPart(TextFormat.Html)
        {
            Text = emailBody
        };

        using (var smtpClient = new SmtpClient())
        {              
            smtpClient.Connect(smtpServer, smtpPort);

            smtpClient.AuthenticationMechanisms.Remove("XOAUTH2");
            smtpClient.Authenticate(smtpUsername, smtpPassword);
            smtpClient.Send(message);
            smtpClient.Disconnect(true);
        }
    }

标签: c#emailasp.net-coresmtpmailkit

解决方案


如果发件人地址不匹配,很多 SMTP 服务器(例如 GMail)会将发件人地址替换为用于身份验证的地址。


推荐阅读