如何使用PowerShell发送电子邮件

时间:2023-01-05 16:25:35

i need some advice in here.. I´d like to send email from powershell so i use this command

我在这里需要一些建议..我想从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)

This command it didnt work for yahoo mail and outlook mail, but works for my gmail. is there anything wrong that i have done?

这个命令它不适用于雅虎邮件和Outlook邮件,但适用于我的Gmail。我做错了什么?

2 个解决方案

#1


18  

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;

#2


4  

I use this:

我用这个:

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

#1


18  

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;

#2


4  

I use this:

我用这个:

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