如何使用powershell v1发送附件的电子邮件?

时间:2010-04-16 11:02:26

标签: powershell

如何使用powershell v1发送带附件的电子邮件?

2 个答案:

答案 0 :(得分:5)

这个功能对我来说效果很好。 。

function send-emailwithattachment( [string] $subject, [string] $body, [object] $to, [Object] $attachment  )
{
    $from = "sender.address@domain.com"
    $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()
}

答案 1 :(得分:0)

尝试使用这个简单的代码,它将帮助您从定义的路径发送电子邮件:$ 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();