programing

PowerShell V2의 Send-Mail Message를 사용하여 Gmail로 메일 보내기

subpage 2023. 7. 28. 22:06
반응형

PowerShell V2의 Send-Mail Message를 사용하여 Gmail로 메일 보내기

PowerShell V2를 사용하는 방법을 찾고 있습니다.Send-MailMessageGmail을 사용합니다.

제가 지금까지 가지고 있는 것은 다음과 같습니다.

$ss = New-Object Security.SecureString
foreach ($ch in "password".ToCharArray())
{
    $ss.AppendChar($ch)
}
$cred = New-Object Management.Automation.PSCredential "uid@example.com", $ss
Send-MailMessage  -SmtpServer smtp.gmail.com -UseSsl -Credential $cred -Body...

다음 오류가 발생합니다.

Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn
 more at
At foo.ps1:18 char:21
+     Send-MailMessage <<<<      `
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

내가 뭔가 잘못하고 있는 것일까요, 아니면Send-MailMessage아직 완전히 구워지지 않았어요 (나는 CTP 3에 있어요.

몇 가지 추가 제한 사항:

  1. 저는 이것이 상호 작용하지 않기를 원하기 때문에 작동하지 않을 것입니다.
  2. 사용자 계정이 Gmail 도메인이 아니라 Google Apps 등록 도메인에 있습니다.
  3. 이 질문에 대해서만 관심이 있습니다.Send-MailMessagecmdlet.일반을 통해 메일을 보내는 중입니다.NET API는 잘 알려져 있습니다.

Gmail용 PowerShell Send-Mail Message 샘플입니다.

테스트를 거쳐 작동하는 솔루션:

$EmailFrom = "notifications@somedomain.com"
$EmailTo = "me@earth.com"
$Subject = "Notification from XYZ"
$Body = "this is a notification from XYZ Notifications.."
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

$SMTPClient에서 $EmailTo 및 사용자 이름/암호를 변경하기만 하면 됩니다.자격 증명...사용자 이름에 include @gmail.com 을 사용하지 마십시오...

이렇게 하면 문제가 해결됩니다.

$credentials = New-Object Management.Automation.PSCredential “mailserver@yourcompany.com”, (“password” | ConvertTo-SecureString -AsPlainText -Force)

그런 다음 통화의 자격 증명을 사용하여Send-MailMessage -From $From -To $To -Body $Body $Body -SmtpServer {$smtpServer URI} -Credential $credentials -Verbose -UseSsl

저도 같은 문제가 있어서 우연히 이 게시물을 보게 되었습니다.실제로 기본 Send-MailMessage 명령어릿으로 실행하는 데 도움이 되었습니다. 코드는 다음과 같습니다.

$cred = Get-Credential
Send-MailMessage ....... -SmtpServer "smtp.gmail.com" -UseSsl -Credential $cred -Port 587 

하지만 SMTP 서버를 사용할 수 있도록 Gmail을 사용하려면 Gmail 계정에 로그인해야 했고, 이 링크 아래에서 https://www.google.com/settings/security 은 "보안이 덜한 앱에 대한 액세스"를 "사용 가능"으로 설정했습니다.그리고 마침내 효과가 있었습니다!!

Gmail은 포트 587에서 작동하기 때문에 Send-Mail Message로 포트 번호를 변경할 수 있는지 모르겠습니다.어쨌든 Gmail로 이메일을 보내는 방법은 다음과 같습니다.NET Smtp 클라이언트:

$smtpClient = New-Object system.net.mail.smtpClient
$smtpClient.Host = 'smtp.gmail.com'
$smtpClient.Port = 587
$smtpClient.EnableSsl = $true
$smtpClient.Credentials = [Net.NetworkCredential](Get-Credential GmailUserID)
$smtpClient.Send('GmailUserID@gmail.com', 'yourself@somewhere.com', 'test subject', 'test message')

Christian의 Feb12 솔루션을 사용했고 PowerShell도 이제 막 배우기 시작했습니다.첨부 파일에 대해서는 Get-Member에서 작동하는 방법을 알아보고 Send()에 두 가지 정의가 있다는 것을 알게 되었습니다.두 번째 정의는 시스템을 사용합니다.넷.메일.첨부 파일과 Cc 및 Bcc와 같은 더 강력하고 유용한 기능을 허용하는 MailMessage 개체입니다.다음은 첨부 파일이 있는 예제입니다(위 예제와 함께 사용).

# append to Christian's code above --^
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
$emailMessage.To.Add($EmailTo)
$emailMessage.Subject = $Subject
$emailMessage.Body = $Body
$emailMessage.Attachments.Add("C:\Test.txt")
$SMTPClient.Send($emailMessage)

맛있게 드세요!

PowerShell은 정말 처음이고 PowerShell에서 gmailing에 대해 검색하고 있었습니다.저는 당신들이 이전 답변에서 했던 것을 가져다가 조금 수정하여 첨부 파일을 추가하기 전에 확인하고 수신자 배열을 가져오는 스크립트를 만들었습니다.

## Send-Gmail.ps1 - Send a gmail message
## By Rodney Fisk - xizdaqrian@gmail.com
## 2 / 13 / 2011

# Get command line arguments to fill in the fields
# Must be the first statement in the script
param(
    [Parameter(Mandatory = $true,
               Position = 0,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('From')] # This is the name of the parameter e.g. -From user@mail.com
    [String]$EmailFrom, # This is the value [Don't forget the comma at the end!]

    [Parameter(Mandatory = $true,
               Position = 1,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('To')]
    [String[]]$Arry_EmailTo,

    [Parameter(Mandatory = $true,
               Position = 2,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Subj')]
    [String]$EmailSubj,

    [Parameter(Mandatory = $true,
               Position = 3,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Body')]
    [String]$EmailBody,

    [Parameter(Mandatory = $false,
               Position = 4,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Attachment')]
    [String[]]$Arry_EmailAttachments
)

# From Christian @ stackoverflow.com
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SMTPClient($SmtpServer, 587)
$SMTPClient.EnableSSL = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAIL_USERNAME", "GMAIL_PASSWORD");

# From Core @ stackoverflow.com
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
foreach ($recipient in $Arry_EmailTo)
{
    $emailMessage.To.Add($recipient)
}
$emailMessage.Subject = $EmailSubj
$emailMessage.Body = $EmailBody
# Do we have any attachments?
# If yes, then add them, if not, do nothing
if ($Arry_EmailAttachments.Count -ne $NULL)
{
    $emailMessage.Attachments.Add()
}
$SMTPClient.Send($emailMessage)

물론 G메일_USERNAME 및 G메일_PASSWORD 값을 특정 사용자와 비밀번호로 변경합니다.

많은 테스트와 해결책에 대한 오랜 검색 끝에 #PSTip에서 기능적이고 흥미로운 스크립트 코드를 Gmail 계정을 사용하여 이메일 보내기 코드를 발견했습니다.

$param = @{
    SmtpServer = 'smtp.gmail.com'
    Port = 587
    UseSsl = $true
    Credential  = 'you@gmail.com'
    From = 'you@gmail.com'
    To = 'someone@somewhere.com'
    Subject = 'Sending emails through Gmail with Send-MailMessage'
    Body = "Check out the PowerShellMagazine.com website!"
    Attachments = 'D:\articles.csv'
}

Send-MailMessage @param

Windows 8.1 컴퓨터에서 다음 스크립트를 사용하여 Gmail을 통해 첨부 파일과 함께 이메일을 보낼 수 있는 Send-Mail Message를 받았습니다.

$EmFrom = "user@gmail.com"
$username = "user@gmail.com"
$pwd = "YOURPASSWORD"
$EmTo = "recipient@theiremail.com"
$Server = "smtp.gmail.com"
$port = 587
$Subj = "Test"
$Bod = "Test 123"
$Att = "c:\Filename.FileType"
$securepwd = ConvertTo-SecureString $pwd -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $securepwd
Send-MailMessage -To $EmTo -From $EmFrom -Body $Bod -Subject $Subj -Attachments $Att -SmtpServer $Server -port $port -UseSsl  -Credential $cred

PowerShell을 사용하여 첨부 파일과 함께 이메일 보내기 -

      $EmailTo = "udit043.ur@gmail.com"  // abc@domain.com
      $EmailFrom = "udit821@gmail.com"  // xyz@gmail.com
      $Subject = "zx"  //subject
      $Body = "Test Body"  // Body of message
      $SMTPServer = "smtp.gmail.com" 
      $filenameAndPath = "G:\abc.jpg"  // Attachment
      $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body)
      $attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
      $SMTPMessage.Attachments.Add($attachment)
      $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
      $SMTPClient.EnableSsl = $true 
      $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("udit821@gmail.com", "xxxxxxxx"); // xxxxxx-password
      $SMTPClient.Send($SMTPMessage)

powershell에서 메일을 보내는 데 필요한 스크립트를 얻는 데 큰 문제가 있었습니다.스크립트에서 인증하려면 지메일 계정에 대한 앱 암호를 만들어야 합니다.이제 완벽하게 작동합니다!

여기 있습니다.

$filename = “c:\scripts_scott\test9999.xls”
$smtpserver = “smtp.gmail.com”
$msg = New-Object Net.Mail.MailMessage
$att = New-Object Net.Mail.Attachment($filename)
$smtp = New-Object Net.Mail.SmtpClient($smtpServer )
$smtp.EnableSsl = $True
$smtp.Credentials = New-Object System.Net.NetworkCredential(“username”, “password_here”); # Put username without the @GMAIL.com or – @gmail.com
$msg.From = “username@gmail.com”
$msg.To.Add(”boss@job.com”)
$msg.Subject = “Monthly Report”
$msg.Body = “Good MorningATTACHED”
$msg.Attachments.Add($att)
$smtp.Send($msg)

그게 당신에게 도움이 된다면 저에게 알려주세요.또한 Www.techjunkie.tv 에서도 이메일 메시지를 사용할 수 있습니다.

그런 식으로 사용하는 것이 훨씬 더 좋고 순수하다고 생각하는 것도 마찬가지입니다.

PowerShell V2의 Send-Mail Message는 사용하지 않았지만 System은 사용했습니다.넷.메일.데모 목적으로 Gmail 계정으로 메시지를 보내는 V1의 SMTPClient 클래스입니다.오버킬일 수 있지만 Windows Vista 노트북에서 SMTP 서버를 실행합니다( 링크 참조).기업에 있는 경우 이미 메일 릴레이 서버가 있으며 이 단계는 필요하지 않습니다.SMTP 서버를 사용하면 다음 코드로 Gmail 계정으로 이메일을 보낼 수 있습니다.

$smtpmail = [System.Net.Mail.SMTPClient]("127.0.0.1")
$smtpmail.Send("myacct@gmail.com", "myacct@gmail.com", "Test Message", "Message via local SMTP")

저는 비록 처음에 스콧 와인스타인이 보고한 오류를 여전히 얻었지만, 크리스찬 머글리의 해결책에 동의합니다.그것을 극복하는 방법은 다음과 같습니다.

지정된 계정을 사용하여 이 계정이 실행될 컴퓨터에서 Gmail에 처음 로그인합니다.(Internet Explorer 보안 강화 구성이 활성화된 경우에도 신뢰할 수 있는 사이트 영역에 Google 사이트를 추가할 필요가 없습니다.)

또는 처음 시도할 때 오류가 표시되고 Gmail 계정에 의심스러운 로그인에 대한 알림이 표시되므로 해당 사용자의 지시에 따라 이 계정이 실행될 컴퓨터에서 나중에 로그인할 수 있습니다.

언급URL : https://stackoverflow.com/questions/1252335/send-mail-via-gmail-with-powershell-v2s-send-mailmessage

반응형