【问题标题】:How to Send an email through "Contact us" Form using Mailkit in asp.net core如何在 asp.net core 中使用 Mailkit 通过“联系我们”表单发送电子邮件
【发布时间】:2019-11-23 14:37:10
【问题描述】:

大家好!

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

我尝试在调试模式下运行我的应用程序,一切似乎都很好。 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# email asp.net-core smtp mailkit


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2021-01-10
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 2013-06-02
      • 2015-08-17
      相关资源
      最近更新 更多