none
Powershell to send an email via Office365 - not working RRS feed

  • Question

  • Hello,

    I've spent the entire day searching the forums and trying different scripts but none seem to work. I do not get any errors but the mail message never arrives nor does it show in the message trace of exchange 365. I can telnet to the port no problem and I can send email via Outlook.

    Here are 3 samples of what i've tried using. Some of the others are a bit more lengthy.

    Please help...thanks!

    --------------

    Try #1

    $host.Runspace.ThreadOptions = "ReuseThread" 

    function Send-EmailByO365 
    {    
     param($O365Cred,$sFromEMail,$sToEMail,$sEMailSubject,$sEMailBody,$sSMTPServer)  
         Try 
         {    
             
         if($sToEmail -ne $null) 
         { 
             [string[]]$To=$sToEMail.Split(',',[System.StringSplitOptions]::RemoveEmptyEntries) 
             Send-MailMessage -From $sFromEMail -To $To -Subject $sEMailSubject -Body $sEMailBody -BodyAsHtml -SmtpServer $sSMTPServer -Credential $O365Cred -UseSsl  
             }     
         } 
         catch [System.Exception] 
         { 
             Write-Host -ForegroundColor Red $_.Exception.ToString()    
         }  
     } 

     $sUserName="<email>" 
     $sMessage="Introduce your Office 365 Credentials" 
     $O365Cred=Get-Credential -UserName $sUserName -Message $sMessage 
    $sFromEMail="<email>" 
    $sToEMail="<email>" 
    $sEMailSubject="<E-Mail Subject>" 
    $sEMailBody="<E-Mail Body (just add your HTML code)>" 
    $sSMTPServer="smtp.office365.com" 
     
    #Sending the e-mail 
    Send-EmailByO365 -O365Cred $O365Cred -sFromEMail $sFromEMail -sToEMail $sToEMail -sEMailSubject $sEMailSubject -sEMailBody $sEMailBody -sSMTPServer $sSMTPServer 

    -------------------

    Try #2

    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { return $true }
    $cred = get-credential
    $body = “Just a test email”
    Send-MailMessage -To <email> -from <email> -Subject 'test' -Body $body -BodyAsHtml -smtpserver smtp.office365.com -usessl -Credential $cred -Port 587 

    -------------------

    Try #3

     [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { return $true }
     $username = '<username>'
     $password = get-content '<path>\mysecurestring.txt' | convertto-securestring
     $smtpcred = new-object -typename system.management.automation.pscredential `
              -argumentlist $username, $password
     
     $toaddress = '<email>'
     $fromaddress = '<email>'
     $smtpserver = 'smtp.office365.com'
     $smtpport = '587'
     $attachment = '<file>'
     $mailparam = @{
     to = $toaddress
     from = $fromaddress
     subject = 'test2'
     body = 'this is a test'
     smtpserver = $smtpserver
     port = $smtpport
     credential = $smtpcred
     attachments = $attachment
     }
     send-mailmessage @mailparam -usessl

    ------------------

    If I don't put this line

     [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { return $true }

    Sometimes I get the following error (of course now im not getting it to copy paste)

    Send-MailMessage : The remote certificate is invalid according to the validation procedure.

    ------------------

    For credentials I've tried both traditional domain\user and AAD using my email address login type

    I've also tried port 25 not using ssl and i've tried my MX record instead of the standard smtp.office365.com


    Life moves pretty fast. If you don't stop and look around once in a while, you could miss it.

    • Moved by Bill_Stewart Friday, March 15, 2019 7:13 PM Not a scripting question
    Thursday, February 7, 2019 9:57 PM

All replies

  • You have to open a support case with MS on the portal to get this repaired. This is one of a number of ongoing issues with O365 and the SMTP access.

    You must -UseSSL and you cannot use port 25. 

     


    \_(ツ)_/



    • Edited by jrv Thursday, February 7, 2019 10:35 PM
    Thursday, February 7, 2019 10:32 PM
  • Do not bypass the certificate test. The cert must be valid or you can have other issues.

    This is the correct way to set this up.

    $username = '<username>'
    $password = get-content '<path>\mysecurestring.txt' | convertto-securestring
    
    $mailparam = @{
        To          = '<email>'
        From        = '<email>'
        Subject     = 'test2'
        Body        = 'this is a test'
        Smtpserver  = 'smtp.office365.com'
        Port        = 587
        Credential  = [system.management.automation.pscredential]::New($username, $password)
        Attachments = $attachment
        UseSsl = $true
    }
    [System.Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    Send-Mailmessage @mailparam
    "$attachment" cannot be null.


    \_(ツ)_/







    • Edited by jrv Thursday, February 7, 2019 10:48 PM
    Thursday, February 7, 2019 10:38 PM
  • You must also enable TLS.  Recently MS stopped supporting SSL but some servers may  not be updated.  All work with TLS.  Not all work with SSL.

    To add TLS add this line.

    [System.Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12

    If on the latest W10 or later TLS12 may already be enabled.


    \_(ツ)_/



    • Edited by jrv Thursday, February 7, 2019 10:48 PM
    Thursday, February 7, 2019 10:46 PM
  • Note that the code posted works and is tested as posted.  It is what I have been using for the last 2 years.  It never fails.  If you still get cert errors then you must contact MS support and have them fix the cause of the bad cert on your portal.

    Mostly these issues are caused by lack of TLS12 being enabled.


    \_(ツ)_/

    Thursday, February 7, 2019 10:55 PM
  • Thanks for the responses. I tried the above with the line

    [System.Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12

    and now I get this:

    Send-Mailmessage : A call to SSPI failed, see inner exception.
    At C:\Users\<path>\desktop\Tasks\test.ps1:18 char:2
    +  Send-Mailmessage @mailparam
    +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], Authentica
       tionException
        + FullyQualifiedErrorId : AuthenticationException,Microsoft.PowerShell.Commands.SendMailMessage



    Life moves pretty fast. If you don't stop and look around once in a while, you could miss it.

    Friday, February 8, 2019 4:54 AM
  • Just run the code I posted.   Only change the authentication and the to/from fields.  If you still get an error then you have issues with your portal.


    \_(ツ)_/

    Friday, February 8, 2019 5:16 AM
  • Yep same thing. I'll open a support case and update if something gets fixed.

    Thanks


    Life moves pretty fast. If you don't stop and look around once in a while, you could miss it.

    Friday, February 8, 2019 5:21 AM
  • I would guess that your SSO has not been set up correctly.  For SMTP authentication you may need to run the SSO module.  I have not enebaled mine on the Admin account.  If you admin account is not set for SSO try it.

    SSPI is the authentication extended method.  The error says it is rejecting your credentials.

    https://docs.microsoft.com/en-us/exchange/mail-flow-best-practices/how-to-set-up-a-multifunction-device-or-application-to-send-email-using-office-3


    \_(ツ)_/

    Friday, February 8, 2019 5:46 AM
  • ah hah, i did not setup SSO yet. I'll do that in the morning.

    Life moves pretty fast. If you don't stop and look around once in a while, you could miss it.

    Friday, February 8, 2019 6:26 AM
  • Enabled SSO still the same error. Support got back to me let me run this by them and see what they say.

    Life moves pretty fast. If you don't stop and look around once in a while, you could miss it.

    Friday, February 8, 2019 4:25 PM