Sending email from script

AMITGUY 181 Reputation points
2023-01-25T18:11:16.29+00:00

I would like to write a simple script to send an email from powershell. This script will eventually be ran as a task scheduler. We are in exchange online environment in a hybrid environment.

Microsoft Exchange Online
Microsoft Exchange Online Management
Microsoft Exchange Online Management
Microsoft Exchange Online: A Microsoft email and calendaring hosted service.Management: The act or process of organizing, handling, directing or controlling something.
4,342 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,446 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Yuki Sun-MSFT 40,931 Reputation points
    2023-01-26T07:37:05.44+00:00

    Hi @AMITGUY ,

    Agree with Andreas that you can try using Send-MailMessage. Below is a sample script for reference:

    Note that you'll need to enable SMTP AUTH in your tenant up front for this to work.

    $username = "user@domain.com"
    $password = "userpassword"
    $sstr = ConvertTo-SecureString -string $password -AsPlainText -Force
    $cred = New-Object System.Management.Automation.PSCredential -argumentlist $username, $sstr
    $body = "This is a test email"
    Send-MailMessage -To "recipient@contoso.com" -From "user@domain.com" -Subject 'Test message' -Body $body -BodyAsHtml -smtpserver smtp.office365.com -usessl -Credential $cred -Port 587
    
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

  2. Andreas Baumgarten 102.1K Reputation points MVP
    2023-01-25T18:38:10.9533333+00:00

    Hi @Adamster2 ,

    you can give Send-MailMessage a try:

    https://video2.skills-academy.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-5.1


    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards

    Andreas Baumgarten

    0 comments No comments

  3. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more