我想在这封电子邮件中发送一个CSV文件。我可以毫无问题地发送电子邮件,但是我尝试了很多方法来发送附件,但是最后发送电子邮件时没有附件。
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
电子邮件只需如下所示:
您好,所有信息都在文件示例中.csv
Send-MailMessage
有一种直接处理附件的方法。下面是示例。
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
,然后你必须使用:
$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)
}
如果需要,请参阅此内容。