Powershell send-mailmessage - email to multiple recipients

前端 未结 7 2095
小蘑菇
小蘑菇 2020-11-29 07:10

I have this powershell script to sending emails with attachments, but when I add multiple recipients, only the first one gets the message. I\'ve read the documentation and s

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 07:40

    to send a .NET / C# powershell eMail use such a structure:

    for best behaviour create a class with a method like this

     using (PowerShell PowerShellInstance = PowerShell.Create())
                {
                    PowerShellInstance.AddCommand("Send-MailMessage")
                                      .AddParameter("SMTPServer", "smtp.xxx.com")
                                      .AddParameter("From", "xxx@xxx.com")
                                      .AddParameter("Subject", "xxx Notification")
                                      .AddParameter("Body", body_msg)
                                      .AddParameter("BodyAsHtml")
                                      .AddParameter("To", recipients);
    
                    // invoke execution on the pipeline (ignore output) --> nothing will be displayed
                    PowerShellInstance.Invoke();
                }              
    

    Whereby these instance is called in a function like:

            public void sendEMailPowerShell(string body_msg, string[] recipients)
    

    Never forget to use a string array for the recepients, which can be look like this:

    string[] reportRecipient = { 
                            "xxx ",
                            "xxx "
                            };
    

    body_msg

    this message can be overgiven as parameter to the method itself, HTML coding enabled!!

    recipients

    never forget to use a string array in case of multiple recipients, otherwise only the last address in the string will be used!!!

    calling the function can look like this:

            mail reportMail = new mail(); //instantiate from class
            reportMail.sendEMailPowerShell(reportMessage, reportRecipient); //msg + email addresses
    

    ThumbUp

提交回复
热议问题