2
votes

How do I send an email containing a binary file using powershell script? Below is my failing best attempt

$to = 'andy.boo@boo.com'
$subject = 'boo'
$file = 'inf.doc'
$from = $to
$filenameAndPath = (Resolve-Path .\$file).ToString()

[void][Reflection.Assembly]::LoadWithPartialName('System.Net') | out-null

$message = New-Object System.Net.Mail.MailMessage($from, $to, $subject, $subject)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath, 'text/plain')
$message.Attachments.Add($attachment)

$smtpClient = New-Object System.Net.Mail.SmtpClient
$smtpClient.host = 'smtp.boo.com'
$smtpClient.Send($message)

Exception calling "Send" with "1" argument(s): "Failure sending mail." At C:\email.ps1:15 char:17 + $smtpClient.Send <<<< ($message) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException

2

2 Answers

4
votes

What version of PowerShell? If you're using version 2.0 save yourself the trouble and just use the Send-MailMessage cmdlet.

If version 1.0:

$msg = new-object system.net.mail.MailMessage
$SMTPClient = new-object system.net.mail.smtpClient
$SMTPClient.host = "smtp server"
$msg.From = "Sender"
$msg.To.Add("Recipient")
$msg.Attachments.Add('<fullPathToFile')
$msg.Subject = "subject"
$msg.Body = "MessageBody"
$SMTPClient.Send($Msg)
0
votes

Found this.. which is a lot better

Send-MailMessage -smtpServer smtp.doe.com -from 'joe@doe.com' -to 'jane@doe.com' -subject 'Testing' -attachment foo.txt