使用PowerShell发送电子邮件

时间:2019-01-02 01:13:44

标签: c# powershell

我有一个能够通过PowerShell发送电子邮件的功能。

使用System.Management.Automation参考,我可以使用PowerShell类,该类允许我添加将发送电子邮件的PowerShell脚本。

如果我直接在PowerShell窗口中键入它,则如下所示:

$password = ConvertTo-SecureString 'PASSWORD' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('sender@email.com', $password)
Send-MailMessage -From 'sender@email.com' -To 'receiver@email.com' -Subject 'Heres the Email Subject' -Body 'This is what I want to say' -SmtpServer 'smtp.office365.com' -Port '587' -UseSsl -Credential $Cred –DeliveryNotificationOption OnSuccess

它可以发送电子邮件,但是我如何检查是否未发送电子邮件?

该功能在下面。

private void SendEmail()
{
    string from = "sender@email.com";
    string to = "receiver@email.com";
    string subject = "Heres the Email Subject";
    string body = "This is what I want to say";
    string server = "smtp.office365.com";
    string port = "587";

    //Password goes here
    string password = "PASSWORD";
    string pw = "ConvertTo-SecureString '" + password + "' -AsPlainText  -Force";

    string cred = "New-Object System.Management.Automation.PSCredential('" + from + "', $password)";
    string send = "Send-MailMessage -From '" + from + "' -To '" + to + "' -Subject '" + subject + "' -Body '" + body + "' -SmtpServer '" + server + "' -Port '" + port + "' -UseSsl -Credential $Cred -DeliveryNotificationOption OnSuccess";
    string psScript = "$password = " + pw + System.Environment.NewLine +
                      "$Cred = " + cred + System.Environment.NewLine +
                      send;

    using (PowerShell ps = PowerShell.Create())
    {
        ps.AddScript(psScript);

        // invoke execution on the pipeline (collecting output)
        Collection<PSObject> PSOutput = ps.Invoke();

        // loop through each output object item
        foreach (PSObject outputItem in PSOutput)
        {
            // if null object was dumped to the pipeline during the script then a null
            // object may be present here. check for null to prevent potential NRE.
            if (outputItem != null)
            {
                //TODO: do something with the output item 
                Console.WriteLine(outputItem.BaseObject.GetType().FullName);
                Console.WriteLine(outputItem.BaseObject.ToString() + "\n");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我找到了一种使用ps.HadErrors检查错误的方法

using (PowerShell ps = PowerShell.Create())
{
     //Add the powershell script to the pipeline
     ps.AddScript(psScript);

     // invoke execution on the pipeline (collecting output)
     Collection<PSObject> PSOutput = ps.Invoke();

     //check for any errors
     if (ps.HadErrors)
     {
         foreach (var errorRecord in ps.Streams.Error)
         {
              Console.WriteLine(errorRecord);
         }
     }

 }