c# - 如何在 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);
}
}
解决方案
如果发件人地址不匹配,很多 SMTP 服务器(例如 GMail)会将发件人地址替换为用于身份验证的地址。
推荐阅读
- java - 在输入中使用空格时 Java 扫描器输入不匹配
- android - 从使用导航组件的片段返回时会触发哪些方法?
- excel - 为什么不显示我的 VBA ListBox 值?
- html - 留出与标题和文章部分相同的高度
- python - 在父类中调用函数并访问父自我
- swift - Swift 关联类型约束
- php - Preg_split 仅一次,忽略之后的任何内容
- angular - 无法测试使用翻译管道的组件(找不到管道“翻译”)
- python - 尝试将数据附加到 Python 中的列时出错
- ruby-on-rails - 如何将 ActiveStorage::Attached::One 移动到 ActiveStorage::Attached::Many?