大家好!
我在使用联系表单发送电子邮件时遇到问题。目标是让用户输入他的电子邮件地址、主题和消息,电子邮件就会显示在我的邮箱中。我遇到的问题是电子邮件不是来自用户输入的电子邮件地址,而是来自应该接收消息的地址。基本上,我一直在给自己发送电子邮件。我向用户发送电子邮件没有问题,例如发票或订单状态...
我尝试在调试模式下运行我的应用程序,一切似乎都很好。发布方法模型具有我输入的值,并且 SendEmail 方法不会将"发件人地址"替换为我的地址。
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(会将发件人地址替换为用于身份验证的地址,如果它们不匹配。