【问题标题】:How to send email with multiple attachments using this code如何使用此代码发送带有多个附件的电子邮件
【发布时间】:2019-12-11 22:10:34
【问题描述】:

我对 PowerShell 了解不多,但我在 Stack Overflow 中找到了有关如何发送带有附件的电子邮件的代码。我想知道是否可以对其进行一些更改,以便我可以发送两个附件而不是一个。我想在不使用 ZIP 或 RAR 压缩的情况下发送文件:

附件: "C:\Users\ricar\Desktop\impressora.txt" "C:\Users\ricar\Desktop\impressora2.txt"

$Username = "myemail@sapo.pt";
$Password = "mypassword";
$path = "C:\Users\ricar\Desktop\impressora.txt";

function Send-ToEmail([string]$email, [string]$attachmentpath){

    $message = new-object Net.Mail.MailMessage;
    $message.From = "myemail@sapo.pt";
    $message.To.Add($email);
    $message.Subject = "Hello how are you";
    $message.Body = "Is this really going to happen?????";
    $attachment = New-Object Net.Mail.Attachment($attachmentpath);
    $message.Attachments.Add($attachment);

    $smtp = new-object Net.Mail.SmtpClient("smtp.sapo.pt", "587");
    $smtp.EnableSSL = $true;
    $smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
    $smtp.send($message);
    write-host "Mail Sent" ; 
    $attachment.Dispose();
 }
Send-ToEmail  -email "myfriend@yahoo.com.br" -attachmentpath $path;

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我将使用[string[]] 为-attachmentpath 参数使用一个字符串数组。您也可以省略创建单独的 Net.Mail.Attachment 对象的步骤,因为它已经包含在您已有的基础 Net.Mail.MailMessage 对象中。

    例子:

    $Username = "myemail@sapo.pt"
    $Password = "mypassword"
    $path = "C:\Users\ricar\Desktop\impressora.txt","C:\Users\ricar\Desktop\impressora2.txt"
    
    function Send-ToEmail([string]$email, [string[]]$attachmentpath){
    
        $message = new-object Net.Mail.MailMessage
        $message.From = "myemail@sapo.pt"
        $message.To.Add($email)
        $message.Subject = "Hello how are you"
        $message.Body = "Is this really going to happen?????"
        $attachmentpath | foreach {$message.Attachments.Add($_)}
    
        $smtp = new-object Net.Mail.SmtpClient("smtp.sapo.pt", "587")
        $smtp.EnableSSL = $true
        $smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
        $smtp.send($message)
        write-host "Mail Sent"  
     }
    Send-ToEmail  -email "myfriend@yahoo.com.br" -attachmentpath $path
    

    此外,无需在 PowerShell 中的每行末尾包含分号。如果它符合当前的代码样式指南,我只会使用它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 2010-09-21
      相关资源
      最近更新 更多