Arunachalam
Arunachalam

Reputation: 6037

how to send an email with attachement using powershell v1?

how to send an email with attachement using powershell v1?

Upvotes: 4

Views: 1941

Answers (2)

Mohit Singh
Mohit Singh

Reputation: 1

Try using this simple code which will help you in sending email from a defined path : $FilesPath

    $smtpServer = "<smtprelay>"
    $msg = new-object Net.Mail.MailMessage

    #Change port number for SSL to 587
    $smtp = New-Object Net.Mail.SmtpClient($SmtpServer, 25) 

    #Uncomment Next line for SSL  
    #$smtp.EnableSsl = $true

    #From Address
    $msg.From = ""
    #To Address, Copy the below line for multiple recipients
    $msg.To.Add("")
    $msg.Cc.Add("")


    #Message Subject
    $msg.Subject = "Test Subject"

    $FilesPath = "C:\testfile.txt"

    $attachment = New-Object System.Net.Mail.Attachment –ArgumentList $FilesPath
    $msg.Attachments.Add($attachment)


    $smtp.Send($msg)
    $msg.Dispose();

Upvotes: 0

Brian
Brian

Reputation: 76

This function has worked well for me . . .

function send-emailwithattachment( [string] $subject, [string] $body, [object] $to, [Object] $attachment  )
{
    $from = "[email protected]"
    $domain  = "smtp-server.domain.com"

    $mail = new-object System.Net.Mail.MailMessage

    for($i=0; $i -lt $to.Length; $i++) {
        $mail.To.Add($to[$i]);
    }

    $mail.From = new-object System.Net.Mail.MailAddress($from)
    $mail.Subject = $subject
    $mail.Body = $body

    $attach = New-Object System.Net.Mail.Attachment($attachment)
    $mail.Attachments.Add($attach)

    $smtp = new-object System.Net.Mail.SmtpClient($domain)
    $smtp.Send($mail)

    $attach.Dispose()
    $mail.Dispose()
}

Upvotes: 5

Related Questions