Search This Blog

Tuesday, November 8, 2022

PowerShell: Send email with attachment

It was when I was working on a hobby project that I did some research on how to send emails using PowerShell.

It wasn't the first time I managed to pull it off but I had forgotten how to script it, so I did some research.

Two parts at least seems to be needed, the credentials for the sender and the necessary variables for the email itself, such as header and content.

In this post I will discuss the credentials first, then the sending part. All this code was tested using PowerShell ISE. Microsoft writes that the cmdlet Send-Mailmessage is a bit outdated, so be wary.

Credentials

Rule number one in scripting: Don't store passwords in plain text, rule number two, don't store it in files that you send to others. Let's break these rules a bit.

We don't need to discuss why storing passwords in plain text is a bad idea, but this is how you can do it.
 
 
$u is your user name, in this case your full legit email address and $p is the plain text password.
Together the make up $c, which is a variable storing your credentials. Make sure to not enclose $p in quotation marks as this causes the code to break.

If you want to store your credentials in another way, you could write $c = Get-Credential; $c but it serves a different purpose than the automation and no sharing idea I had with my project.

Sending the email

This code shows your a cmdlet that takes related parameters (and a lot of them).
 
Send-MailMessage -To $receiver -From $u -Subject “Autoreply” -Body “What the main part of the mail contains.” -Attachments "c:\temp\log.txt" -Credential $c -SmtpServer “outlook.office365.com” -Port 587 -UseSsl

You need to find the right port and smtp server for your email provider. In this example I used Outlook. I couldn't send the mail without the "-usessl". Instead of a storing credentials in a variable, you can supply the "-credential" parameter with (Get-Credential) instead. The parenthesis helps prioritize the credentials.
 

Conclusion

Using the above code my script managed to send a file to the receiving email address.
However the script does not let you spoof the sender address provided in the send-mailmessage cmdlet. It has to be the same as the credential. I did not experience any trouble receiving the mail or attachments.


No comments:

Post a Comment