Sending E-Mail with attachment in PowerShell

2019-08-20 07:57发布

问题:

I want to send a CSV file in this e-mail. I can send the email with no problem, but I tried a lot to send attachment with it, but at the end the e-mail was sent without the attachment.

function sendmail($Body) {
    $Smtp = New-Object System.Net.Mail.SmtpClient
    $MailMessage = New-Object System.Net.Mail.MailMessage
    $Smtp.Host = "smtp-server"
    $MailMessage.From = "sender@example.com"
    $MailMessage.To.Add("recipient@example.org")
    $MailMessage.Subject = "Hello"

    $MailMessage.Body = $Body

    $smtp.Port = 25
    $smtp.EnableSsl = $false

    $Smtp.Send($MailMessage)
} 

$Body = "12334"
sendmail $Body

The e-mail just have to look like this:

Hello, all the information are in the file Example.csv

回答1:

Send-MailMessage has a direct way of handling the attachments. Below is the sample.

Send-MailMessage -From "User01 <user01@example.com>" `
                       -To "User02 <user02@example.com>", `
                           "User03 <user03@example.com>" `
                       -Subject "Sending the Attachment" `
                       -Body "Forgot to send the attachment. Sending now." `
                       -Attachment "data.csv" -SmtpServer smtp.fabrikam.com

OR, you should use System.Net.Mail.MailMessage, then you have to use:

$EmailFrom = "<user@domain.tld>"
$EmailTo = "<user@domain.tld>"
$EmailSubject = "<email subject"  

$SMTPServer = "smtphost.domain.tld"
$SMTPAuthUsername = "username"
$SMTPAuthPassword = "password"

$emailattachment = "<full path to attachment file.csv>"

function send_email {
    $mailmessage = New-Object System.Net.Mail.MailMessage 
    $mailmessage.From = ($emailfrom) 
    $mailmessage.To.Add($emailto)
    $mailmessage.Subject = $emailsubject
    $mailmessage.Body = $emailbody

    $attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'text/plain')
    $mailmessage.Attachments.Add($attachment)

    #$mailmessage.IsBodyHTML = $true
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)  
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword") 
    $SMTPClient.Send($mailmessage)
}

Refer THIS if required.