简体   繁体   中英

Send email through powershell not working

I'm working on a script to send email to people through powershell. It send well on some computer, but on others it doesn't send at all I know that both computers are not configured exactly the same.

I can't figure why.

I tried adding 2>> c:\\error.txt at the end of the command and it is not logging anything.

My code (I changer the smtp and email for confidentiality reasons):

            File.Delete(@"C:\Temp\Email2Send.ps1");
            var strVar_EMAIL_BOX = "myemail@email.com";
            TextWriter tw = new StreamWriter(@"C:\Temp\Email2Send.ps1");
            tw.WriteLine("$OutputEncoding = [Console]::OutputEncoding");
            tw.WriteLine("$smtp = \"forwarder.mail.xxxxxx.com\"");
            tw.WriteLine("$to = \"" + To + "\"");
            tw.WriteLine("$from = \"" + strVar_EMAIL_BOX + "\"");
            tw.WriteLine("$enc = [System.Text.Encoding]::UTF8");
            tw.WriteLine("$subject = \"Suivi\"");
            tw.WriteLine("$body = \"" + Body + "\"");
            tw.WriteLine(@"send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Encoding $enc 2>> c:\errors.txt");
            tw.Close();
        }

        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = @"/C powershell -ExecutionPolicy Bypass -WindowStyle Hidden -command c:\Temp\Email2Send.ps1";
        process.StartInfo = startInfo;
        process.Start();

EDIT : Nevermind I found the solution 2 seconds after posting. for some reason powershell is not linked correctly on some computer in the windows path. Changed powershell to : %SYSTEMROOT%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe

I found the solution 2 seconds after posting. for some reason powershell is not linked correctly on some computer in the windows path. Changed powershell to : %SYSTEMROOT%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM