전자 메일을 보내기 위해 Send-MailMessage 명령에 자격 증명을 전달하는 방법
저는 제 자격 증명을 FBI에 전달하는 데 어려움을 겪고 있습니다.Send-MailMessage
지휘권
다음은 제가 실행하는 것입니다.
Send-MailMessage -smtpServer smtp.gmail.com -from 'myself@gmail.com' `
-to 'myself@gmail.com' -subject 'Test' -attachment C:\CDF.pdf
메시지 아래에 오류가 있습니다. 이는 분명히 제가 지메일 자격 증명을 전달하지 않았기 때문입니다.
Send-MailMessage : The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first.
나는 구글을 조금 검색했고 또한 man 페이지를 뒤졌습니다.Send-MailMessage
그리고 "-실질적" 매개 변수가 전달되어야 한다는 것을 발견했습니다.
내 문제는: 어떻게?
아래와 같이 Get-Credentials를 사용해 보았습니다.
$mycredentials = Get-Credential
그런 다음 나타나는 상자에 gmail에 대한 내 사용자 이름과 비밀번호를 입력합니다.
그 다음 명령에 따라 실행합니다.
Send-MailMessage -smtpServer smtp.gmail.com -credentail $mycredentials `
-from 'myself@gmail.com' -to 'myself@gmail.com' -subject 'Test' -attachment C:\CDF.pdf
하지만 여전히 똑같은 오류로 실패합니다.
그래서 저는 제 자격 증명을 어떻게 전달하는지에 대해 여러분의 도움이 필요합니다.Send-MailMessage
지휘권저는 PS 자격 증명에 대해 배웠지만, 그것이 무엇인지 그리고 이 맥락에서 어떻게 사용하는지 정확히 알지 못합니다.
다음 블로그 사이트를 찾았습니다.아담 카타바
저는 또한 이 질문을 찾았습니다: send-mail-vmail-with-powershell-v2s-send-mail 메시지.
문제는 두 가지 모두 귀하의 요구 사항(암호 첨부 파일)을 모두 충족하지 못했기 때문에 두 가지를 조합하여 다음과 같이 생각해 냈습니다.
$EmailTo = "myself@gmail.com"
$EmailFrom = "me@mydomain.com"
$Subject = "Test"
$Body = "Test Body"
$SMTPServer = "smtp.gmail.com"
$filenameAndPath = "C:\CDF.pdf"
$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("username", "password");
$SMTPClient.Send($SMTPMessage)
저는 사물을 위한 기능을 만드는 것을 좋아하고, 제가 얻을 수 있는 모든 연습이 필요하기 때문에, 저는 계속해서 다음과 같이 썼습니다.
Function Send-EMail {
Param (
[Parameter(`
Mandatory=$true)]
[String]$EmailTo,
[Parameter(`
Mandatory=$true)]
[String]$Subject,
[Parameter(`
Mandatory=$true)]
[String]$Body,
[Parameter(`
Mandatory=$true)]
[String]$EmailFrom="myself@gmail.com", #This gives a default value to the $EmailFrom command
[Parameter(`
mandatory=$false)]
[String]$attachment,
[Parameter(`
mandatory=$true)]
[String]$Password
)
$SMTPServer = "smtp.gmail.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
if ($attachment -ne $null) {
$SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
$SMTPMessage.Attachments.Add($SMTPattachment)
}
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("@")[0], $Password);
$SMTPClient.Send($SMTPMessage)
Remove-Variable -Name SMTPClient
Remove-Variable -Name Password
} #End Function Send-EMail
호출하려면 다음 명령을 사용합니다.
Send-EMail -EmailTo "Myself@gmail.com" -Body "Test Body" -Subject "Test Subject" -attachment "C:\cdf.pdf" -password "Passowrd"
비밀번호를 그렇게 간단하게 입력하는 것은 안전하지 않다는 것을 알고 있습니다.나중에 더 안전한 방법을 생각해 보고 업데이트할 수 있는지 알아보겠습니다. 하지만 적어도 이 방법을 사용하면 시작하는 데 필요한 작업을 수행할 수 있습니다.즐거운 한 주 보내세요!
편집: 추가됨$EmailFrom
후안 파블로의 논평에 근거하여.
편집: 첨부 파일에서 SMTP의 철자가 STMP입니다.
그리고 여기 간단한 것이 있습니다.Send-MailMessage
단지 그것을 찾는 모든 사람들을 위한 사용자 이름/암호가 있는 예
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From 'sender@gmail.com' -To 'recipient@gmail.com' -Subject 'TEST'
모든 것을 결합하고, 약간의 보안을 만들고, Gmail로 작동시키는 데 시간이 걸렸습니다.저는 이 답변이 누군가에게 시간을 절약해 주기를 바랍니다.
암호화된 서버 암호를 사용하여 파일을 만듭니다.
Powershell에 다음 명령을 입력합니다(내 암호를 실제 암호로 바꿉니다).
"myPassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\EmailPassword.txt"
파워셸 스크립트를 만듭니다(예: sendEmail.ps1).
$User = "usernameForEmailPassword@gmail.com"
$File = "C:\EmailPassword.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString)
$EmailTo = "emailTo@yahoo.com"
$EmailFrom = "emailFrom@gmail.com"
$Subject = "Email Subject"
$Body = "Email body text"
$SMTPServer = "smtp.gmail.com"
$filenameAndPath = "C:\fileIwantToSend.csv"
$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($cred.UserName, $cred.Password);
$SMTPClient.Send($SMTPMessage)
작업 스케줄러를 통한 자동화:
다음을 사용하여 배치 파일(예: emailFile.bat)을 생성합니다.
powershell -ExecutionPolicy ByPass -File C:\sendEmail.ps1
배치 파일을 실행할 작업을 만듭니다.참고: 암호를 암호화할 때 사용한 것과 동일한 사용자 계정으로 작업을 실행해야 합니다! (로그인한 사용자일 수 있음)
이상입니다. 이제 Windows 작업 스케줄러 및 Powershell을 사용하여 전자 메일 및 첨부 파일 전송을 자동화하고 예약할 수 있습니다.타사 소프트웨어가 없으며 암호는 일반 텍스트로 저장되지 않습니다(허용되지만 매우 안전하지도 않음).
전자 메일 암호에 대한 보안 수준에 대한 이 문서도 읽을 수 있습니다.
PSH> $209 = 자격 증명 가져오기
PSH> $cred | 내보내기-CliXml c:\temp\cred.clixml
PSH> $ssh2 = Import-CliXml c:\cli\clis.clixml
이는 사용자의 SID 및 시스템의 SID에 해시되므로 다른 시스템이나 다른 사용자의 손에서 파일을 사용할 수 없습니다.
그래서.. SSL 문제였군요제가 하고 있는 일은 전적으로 옳았습니다.단지 ssl 옵션을 사용하지 않았다는 것입니다.그래서 "-Usessl true"를 원래 명령에 추가했고 작동했습니다.
UseSsl 외에도 작동하려면 smtp 포트 587을 포함해야 합니다.
Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From 'yyy@gmail.com' -To 'xxx@email.com' -Subject 'TEST'
다른 답변과 함께, 만약 당신이 2가지 인증을 가지고 있다면, 당신의 구글 계정에 애플리케이션 비밀번호를 만들어야 할 것이라는 것을 지적하고 싶습니다.
자세한 설명은 https://support.google.com/accounts/answer/185833 .
언급URL : https://stackoverflow.com/questions/12460950/how-to-pass-credentials-to-the-send-mailmessage-command-for-sending-emails
'programing' 카테고리의 다른 글
메인 스레드에서 메서드를 호출하시겠습니까? (0) | 2023.08.05 |
---|---|
Swift UI 해제 모달 (0) | 2023.08.05 |
Oracle Insert via 한 테이블에 행이 없을 수 있는 여러 테이블 중에서 선택 (0) | 2023.08.05 |
'root@localhost' 사용자에 대한 액세스가 거부되었습니다(암호 사용:아니오) (0) | 2023.08.05 |
오류와 함께 npm 설치 오류: ENOENT, chmod (0) | 2023.08.05 |