Carlo V. Dango
Carlo V. Dango

Reputation: 13832

powershell send email with binary attachment

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

$to = '[email protected]'
$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

Upvotes: 3

Views: 3581

Answers (2)

Steven Presley
Steven Presley

Reputation: 116

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)

Upvotes: 4

Carlo V. Dango
Carlo V. Dango

Reputation: 13832

Found this.. which is a lot better

Send-MailMessage -smtpServer smtp.doe.com -from '[email protected]' -to '[email protected]' -subject 'Testing' -attachment foo.txt

Upvotes: 1

Related Questions