sourcetip

PowerShell로 이메일 보내는 방법

fileupload 2023. 11. 4. 13:16
반응형

PowerShell로 이메일 보내는 방법

PowerShell에서 이메일을 보내고 싶어서 다음 명령을 사용합니다.

$EmailFrom = "customer@yahoo.com"
$EmailTo = "receiver@ymail.com"  
$Subject = "today date"
$Body = "TODAY SYSTEM DATE=01/04/2016  SYSTEM TIME=11:32:05.50"
$SMTPServer = "smtp.mail.yahoo.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)   
$SMTPClient.EnableSsl = $true    
$SMTPClient.Credentials = New-Object 
System.Net.NetworkCredential("customer@yahoo.com", "password")    
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

이 명령어는 Yahoo 메일이나 Outlook 메일에서는 작동하지 않았지만 Gmail에서는 작동합니다.제가 잘못한 게 있나요?

다음 코드 조각이 저에게 정말 적합합니다.

$Username = "MyUserName";
$Password = "MyPassword";
$path = "C:\attachment.txt";

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

    $message = new-object Net.Mail.MailMessage;
    $message.From = "YourName@gmail.com";
    $message.To.Add($email);
    $message.Subject = "subject text here...";
    $message.Body = "body text here...";
    $attachment = New-Object Net.Mail.Attachment($attachmentpath);
    $message.Attachments.Add($attachment);

    $smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com", "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 "reciever@gmail.com" -attachmentpath $path;

나는 이것을(를)

Send-MailMessage -To hi@abc.com -from hi2@abc.com -Subject 'hi' -SmtpServer 10.1.1.1

간단히 Gmail smtp를 사용하시면 됩니다.

다음은 첨부 파일과 함께 gmail 메시지를 보내는 파워셸 코드입니다.

    $Message = new-object Net.Mail.MailMessage 
    $smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com", 587) 
    $smtp.Credentials = New-Object System.Net.NetworkCredential("From@gmail.com", "password"); 
    $smtp.EnableSsl = $true 
    $smtp.Timeout = 400000  
    $Message.From = "From@gmail.com" 
    $Message.To.Add("To@gmail.com") 
    $Message.Attachments.Add("C:\foo\attach.txt") 
    $smtp.Send($Message)

보낸 사람 Google 계정(From@gmail.com )에서,

Google Account Security Dashboard(구글 계정 보안 대시보드)에서 보안이 덜한 앱에 대한 액세스를 설정했는지 확인합니다.

마지막으로 이 스크립트를 메일로 저장합니다.ps1

명령 프롬프트 또는 배치 파일에서 아래 스크립트 단순 실행을 호출하려면:

    Powershell.exe -executionpolicy remotesigned -File mail.ps1

기본적으로 큰 첨부 파일 전송의 경우 시간 초과는 약 100초 정도입니다.이 대본에서는 5분에서 6분 정도로 늘어납니다.

EnableSsl을 false로 설정해야 하는 경우가 있습니다(이 경우 네트워크를 통해 메시지가 암호화되지 않은 상태로 전송됨).

언급URL : https://stackoverflow.com/questions/36355271/how-to-send-email-with-powershell

반응형