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.

Exchange Online
Exchange Online
A Microsoft email and calendaring hosted service.
6,171 questions
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Yuki Sun-MSFT 41,376 Reputation points Moderator
    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 = "******@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 "******@contoso.com" -From "******@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 123.4K Reputation points MVP Volunteer Moderator
    2023-01-25T18:38:10.9533333+00:00

    Hi @Adamster2 ,

    you can give Send-MailMessage a try:

    https://learn.microsoft.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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.