在PowerShell中发送带有附件的电子邮件 [英] Sending E-Mail with attachment in PowerShell

查看:541
本文介绍了在PowerShell中发送带有附件的电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在此电子邮件中发送CSV文件. 我可以毫无问题地发送电子邮件,但是我尝试了很多发送附件的方法,但是最后电子邮件没有附件地发送了.

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:

您好,所有信息都在文件Example.csv

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

推荐答案

Send-MailMessage具有处理附件的直接方法.下面是示例.

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

或者,您应该使用System.Net.Mail.MailMessage,然后必须使用:

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)
}

请参阅 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆