Sending mail with PowerShell

The process to send mail is pretty simple.
It’s the attachment process that gets a little complicated.
I found this at…

Which answered the question, How do I attach a file?

[System.Net.Mail.Attachment] $attachment = new-object
System.Net.Mail.Attachment $file

It is necessary to cast the $attachment variable to type
System.Net.Mail.Attachment, since new-object (in this instance)
returns a REFERENCE to an object of that type, not an ACTUAL OBJECT of
the type. But $msg.Attachments.Add($attachment) requires an actual
object. Hence the need for the cast.

So, here is my working code, enjoy!
#<————– Begin —————————————–>
$file = "r:dailylog.txt" <—-the file you want to attach
$sender = ""
$recipient = ""
$server = ""
$subject = "Sending a File " + [System.DateTime]::Now
$body = "I’m sending a file!"
$msg = New-Object System.Net.Mail.MailMessage $sender, $recipient, $subject, $body
$attachment = New-Object System.Net.Mail.Attachment $file
$client = new-object System.Net.Mail.SmtpClient $server
$client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

from Shay Levy
Windows PowerShell MVP
PowerShell Toolbar:

To add 2 recipients
In the same way add cc and bcc:

To compare and contrast here is basicaly the same thing in vbScript;
adminmail = ""

 smtp = "mail_server name or IP"
 Set mailing = CreateObject("CDO.Message")
 Set wshNet = CreateObject("WScript.Network")
 mailing.From = ("")
 mailing.To = adminmail
 mailing.Configuration.Fields.Item ("") = 2
 mailing.Configuration.Fields.Item ("") = smtp
 mailing.Configuration.Fields.Item ("") = 25
 mailing.Subject = header & "Data Transfer Success logs"
 sFullProductionMessage = "See attached file…"  & vbcrlf
 mailing.TextBody = sFullProductionMessage
 mailing.AddAttachment "R:dailylog.txt"
 On Error Goto 0
‘<—————————- END ———————————–>
What if you wanted the Attachment to be the body text?
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
‘Open the file for reading
Set f = fso.OpenTextFile("C:SendLogsdailylog.txt", ForReading)
‘The ReadAll method reads the entire file into the variable BodyText
BodyText = f.ReadAll
‘Close the file
Set f = Nothing
Set fso = Nothing
And in your message function or sub or whatever;
 mailing.TextBody = BodyText
How about CC?
 If you want to send an SMS (text) msg to a phone, just use the phone number and the appropriate SMTP gateways.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s