sourcetip

Powershell 전자 메일 메시지 - 여러 수신자에게 보내는 전자 메일

fileupload 2023. 9. 5. 20:44
반응형

Powershell 전자 메일 메시지 - 여러 수신자에게 보내는 전자 메일

첨부 파일이 포함된 전자 메일을 보낼 수 있는 이 파워셸 스크립트가 있지만 여러 수신자를 추가하면 첫 번째 수신자만 메시지를 받습니다.저는 그 문서를 읽었는데 아직도 그것을 이해할 수 없습니다.감사해요.

$recipients = "Marcel <marcel@turie.eu>, Marcelt <marcel@nbs.sk>"

Get-ChildItem "C:\Decrypted\" | Where {-NOT $_.PSIsContainer} | foreach {$_.fullname} |
send-mailmessage -from "primasfrb@nbs.sk" `
            -to "$recipients" `
            -subject "New files" `
            -body "$teloadmin" `
            -BodyAsHtml `
            -priority  High `
            -dno onSuccess, onFailure `
            -smtpServer  192.168.170.61
$recipients = "Marcel <marcel@turie.eu>, Marcelt <marcel@nbs.sk>"

의 유형입니다.string로의 통행증이 필요합니다.send-mailmessage a string[]유형(어레이):

[string[]]$recipients = "Marcel <marcel@turie.eu>", "Marcelt <marcel@nbs.sk>"

저는 권력 껍질의 강압적인 규칙을 위해 캐스팅을 하지 않는다고 생각합니다.

$recipients = "Marcel <marcel@turie.eu>", "Marcelt <marcel@nbs.sk>"

이라object[]같은 작업을 수행할 수 있습니다.

Powershell 배열을 만드는 것만으로도 효과가 있습니다.

$recipients = @("Marcel <marcel@turie.eu>", "Marcelt <marcel@nbs.sk>")

첨부 파일에 동일한 접근 방식을 사용할 수 있습니다.

$attachments = @("$PSScriptRoot\image003.png", "$PSScriptRoot\image004.jpg")

먼저 다음과 같이 문자열을 문자열 배열로 변환해야 합니다.

$recipients = "Marcel <marcel@turie.eu>,Marcelt <marcel@nbs.sk>"
[string[]]$To = $recipients.Split(',')

사용할 경우Send-MailMessage다음과 같이:

Send-MailMessage -From "primasfrb@nbs.sk" -To $To -subject "New files" -body "$teloadmin" -BodyAsHtml -priority High -dno onSuccess, onFailure -smtpServer 192.168.170.61

여기 완전한 (Gmail) 간단한 해결책이 있습니다...그냥 일반 구분 기호를 사용합니다.아스파라거스를 통과하기에 가장 좋습니다.

$to = "user1@domain.org;user2@domain.org"
$user = "italerts@domain.org"    
$pass = "password"

$pass = ConvertTo-SecureString -String $pass -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential $user, $pass
$mailParam = @{
    To = $to.Split(';')
    From = "IT Alerts <italerts@domain.org>"
    Subject = "test"
    Body = "test"
    SmtpServer = "smtp.gmail.com"
    Port = 587 #465
    Credential = $cred
    UseSsl = $true
}

# Send Email
Send-MailMessage @mailParam

Google 메일에 대한 참고 사항

  • 이것은 "안전하지 않은 앱" 옵션이 활성화된 경우 Gmail과 함께 작동하지만 활성화하지 않아야 합니다.
  • "보안 수준이 낮은 앱" 대신 2단계 인증을 활성화하고 "앱 비밀번호"를 사용합니다.
  • 587이 작동하지 않으면 포트 465를 사용합니다.

문자열 배열을 정의하려면 $var = @('User1', 'User2')를 사용하는 것이 더 편합니다.

$servername = hostname
$smtpserver = 'localhost'
$emailTo = @('username1 <user1@dom.com>', 'username2<user2@dom.com>')
$emailFrom = 'SomeServer <user3@dom.com>'
Send-MailMessage -To $emailTo -Subject 'Low available memory' -Body 'Warning' -SmtpServer $smtpserver -From $emailFrom

복잡한 주물이나 배열로 분할할 필요가 없습니다.구문을 다음과 같이 변경하여 간단히 해결했습니다.

$recipients = "user1@foo.com, user2@foo.com"

대상:

$recipients = "user1@foo.com", "user2@foo.com"

맞습니다, 각 주소는 견적이 필요합니다.명령줄에 여러 개의 주소가 나열되어 있는 경우 사용자에게 친숙한 주소와 전자 메일 주소 부분을 모두 지정하면 발송-메일 메시지가 이 주소를 선호합니다.

…을 보냅니다.NET / C# powershell eMail은 다음과 같은 구조를 사용합니다.

최상의 행동을 위해 다음과 같은 방법으로 클래스를 만듭니다.

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

이러한 인스턴스를 다음과 같은 함수로 호출합니다.

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

수신인에 대해 다음과 같은 문자열 배열을 사용하는 것을 잊지 마십시오.

string[] reportRecipient = { 
                        "xxx <xxx.Fercher@xxx.com>",
                        "xxx <xxx@xxx.com>"
                        };

body_msg

이 메시지는 메서드 자체에 대한 매개 변수로 넘겨질 수 있습니다. HTML 코딩이 활성화되었습니다!

수취인

여러 수신자의 경우 문자열 배열을 사용하는 것을 잊지 마십시오. 그렇지 않으면 문자열의 마지막 주소만 사용됩니다!

함수 호출은 다음과 같습니다.

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

엄지손가락 위로

Powershell SendGrid를 사용하여 Azure VM에서 더 많은 수신자에게 메일을 보내는 완벽한 솔루션:


# Set your API Key here
$sendGridApiKey = '......your Sendgrid API key'
# (only API permission to send mail is sufficient and safe')

$SendGridEmail = @{

    # Use your verified sender address.
    From = 'my@email.com'

    # Specify the email recipients in an array.
    To =  @('person01@domainA.com','person02@domainB.com')

    Subject = 'This is a test message via SendGrid'

    Body = 'This is a test message from Azure send by Powershell script on VM using SendGrid in Azure'
    
    # DO NO CHANGE ANYTHING BELOW THIS LINE
    SmtpServer = 'smtp.sendgrid.net'
    Port = 587
    UseSSL = $true
    Credential = New-Object PSCredential 'apikey', (ConvertTo-SecureString $sendGridApiKey -AsPlainText -Force) 
}

# Send the email
Send-MailMessage @SendGridEmail

Azure에 있는 VM 중 하나에서 Powershell 5.1로 테스트했습니다.

언급URL : https://stackoverflow.com/questions/10241816/powershell-send-mailmessage-email-to-multiple-recipients

반응형