0

I am trying to send email using office365 but facing this issue :

Additional information: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [MA1PR01CA0073.INDPRD01.PROD.OUTLOOK.COM]

My code to send email is :

 var fromAddress = new MailAddress("email", "Relay");
        var toAddress = new MailAddress("email");
        const string fromPassword = "password";
        const string subject = "Subject";
        const string body = "Body";

        var smtp = new SmtpClient
        {
            Host = "smtp.office365.com",
            Port = 587,
            EnableSsl = true,

            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            TargetName = "STARTTLS/smtp.office365.com",
            Credentials = new NetworkCredential(fromAddress.Address, fromPassword, "islandenergyservices.com")
        };
        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        })
        {
            smtp.Send(message);
        }
Amita
  • 21
  • 1
  • 4

2 Answers2

1

I've run into this problem before. It's a stupid little quirk with the order in which you set attributes on the client - you have to set the DefaultCredentials before you do anything else, and then you'll be fine.

See this answer.

Community
  • 1
  • 1
jropella
  • 589
  • 5
  • 14
-1

I had success with the following:

# Sending an email from PowerShell 5.1 script through outlook.office365.com
#
# 1. Create an encrypted password file
#   PS > Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File -FilePath <passwordfile>
#   This will prompt you for a password, encrypt and save in <passwordfile>
# 2. Obtain Outlook Office365 SMTP server name.
#   Go to your ISP and find the value of the MX record. For example <yourdomain>.mail.protection.outlook.com
# 3. If after running the script you get this error:
#   Send-MailMessage : Mailbox unavailable. The server response was: 5.7.606 Access denied, banned sending IP [X.X.X.X].
#   You will need to delist your IP by going here: https://sender.office.com/
#   Note:  Removing you IP from the block list could take up to 30 minutes.
#
$User = "<SMPT loging username>"
$PasswordFile = "<passwordfile>"
$SMTPCredentials=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString)
$EmailTo = "<to email address>"
$EmailFrom = "<from email address>"
$Subject = "<email subject>" 
$Body = "<email body>" 
$SMTPServer = "<Outlook STMP Server from MX record>"
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port 25 -Credential $SMTPCredentials -UseSsl
INFOequipt
  • 29
  • 5