1

I'm trying to send emails in .NET over SMTP. I linked serval custom aliases to the account in office365. (For example no-reply@domain-a.com, no-reply@domain-b.com)

But the mails arrive from No-Reply@mydomain.onmicrosoft.com. Even if I pass in a custom domain in the "from" parameter.

Here is my code:

  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;
                }

As username I'm using myaccount@mydomain.onmicrosoft.com. What am I missing here? Nothing should be wrong with the office365/domain config cause it works when I'm trying to send the mail using 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 
Enrico
  • 2,734
  • 1
  • 27
  • 40

2 Answers2

0

Both Google (GMail) and Microsoft (Office365) replace the From header with the email address of the account used to send the mail in order to curtail spoofing.

If you do not want this, then you'll need to use another SMTP server or set up your own.

jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • Not true, it works when I send the mail to my person email account (or any account outside my organisation) – Enrico Feb 23 '21 at 11:16
0

I found out that it works when sending the email to my personal Gmail. Meaning that there is nothing wrong with the code, but a configuration problem in my office365 / AD domain.

Apparently the outlook "address book" automatically fills in the "from / sender" part in the email, caused because I was sending an mail to the same domain as the one used for my SMTP account. (for example me@domain-a.com and noreply@domain-a.com).

Enrico
  • 2,734
  • 1
  • 27
  • 40