.NET:无法从 SMTP 电子邮件中更改

.NET : Unable to change from in SMTP email

我正在尝试通过 SMTP 在 .NET 中发送电子邮件。我将 serval 自定义别名链接到 office365 中的帐户。 (例如no-reply@domain-a.com, no-reply@domain-b.com)

但是邮件来自 No-Reply@mydomain.onmicrosoft.com。即使我在“from”参数中传入自定义域。

这是我的代码:

  var smtpClient = new SmtpClient(_settings.Endpoint, int.Parse(_settings.Port))
                {
                    UseDefaultCredentials = false,
                    EnableSsl = true,
                    Credentials = new NetworkCredential(_settings.UserName, _settings.Password),
                };

                var mailMessage = new MailMessage
                {
                    From = new MailAddress(message.From.Email, message.From.Name),
                    Subject = message.Subject,
                    Body = message.HtmlMessage,
                    IsBodyHtml = true
                };

                foreach (var addressee in message.Tos)
                {
                    mailMessage.To.Add(addressee.Email);
                }

                try
                {
                    smtpClient.Send(mailMessage);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Error sending email");
                    throw;
                }

作为用户名,我使用 myaccount@mydomain.onmicrosoft.com。 我在这里错过了什么? office365/domain 配置应该没有问题,因为它在我尝试使用 powershell

发送邮件时有效
$O365Cred = Get-Credential #the myaccount@mydomain.onmicrosoft.com credentials

$sendMailParams = @{
    From = 'no-reply@mydomain-a.com'
    To = 'me@gmail.com'
    Subject = 'some subject'
    Body = 'some body'
    SMTPServer = 'smtp.office365.com'
    Port = 587
    UseSsl = $true
    Credential = $O365Cred
}

Send-MailMessage @sendMailParams 

Google (GMail) 和 Microsoft (Office365) 都将发件人 header 替换为用于发送邮件的帐户的电子邮件地址,以减少欺骗。

如果您不想这样做,则需要使用其他 SMTP 服务器或设置您自己的服务器。

我发现在将电子邮件发送到我的个人 Gmail 时它可以工作。意思是代码没有问题,但是我的office365/AD域配置有问题

显然,outlook 的“地址簿”会自动填写电子邮件中的“发件人/发件人”部分,这是因为我将邮件发送到与我的 SMTP 帐户所用的域相同的域。 (例如 me@domain-a.com 和 noreply@domain-a.com)。