How to send email with PowerShell

后端 未结 4 1929
南笙
南笙 2020-12-30 03:48

I\'d like to send email from PowerShell, so I use this command:

$EmailFrom = \"customer@yahoo.com\"
$EmailTo = \"receiver@ymail.com\"  
$Subject = \"today da         


        
相关标签:
4条回答
  • 2020-12-30 04:10

    You can simply use the Gmail smtp.

    Following is The powershell code to send a gmail message with an Attachment:

        $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)
    

    On the sender Google Account (From@gmail.com),

    Make sure you have Turned ON Access for less-secure apps option, from google Account Security Dashboard.

    Finally, Save this Script As mail.ps1

    To invoke the above Script Simple run below on Command Prompt or batch file:

        Powershell.exe -executionpolicy remotesigned -File mail.ps1
    

    By Default, For sending Large Attachments Timeout is Around 100 seconds or so. In this script, it is increased to Around 5 or 6 minutes

    0 讨论(0)
  • 2020-12-30 04:10

    Sometimes you may need to set the EnableSsl to false (in this case the message will be sent unencrypted over the network)

    0 讨论(0)
  • 2020-12-30 04:12

    I use this:

    Send-MailMessage -To hi@abc.com -from hi2@abc.com -Subject 'hi' -SmtpServer 10.1.1.1
    
    0 讨论(0)
  • 2020-12-30 04:19

    Following code snippet really works for me:

    $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;
    
    0 讨论(0)
提交回复
热议问题