I want to send an e-mail using PowerShell commands in a batch file. To do this, I implemented a function called sendMail. I'm calling it like this:
setlocal enabledelayedexpansion
call:sendMail
powershell -command "!_mailCommand!"
endlocal
pause&goto:eof
And my sendMail function:
:sendMail
set "_mailCommand=&{$filenameAndPath = '!resultFile!';"
set "_mailCommand=%_mailCommand%$SMTPMessage = New-Object System.Net.Mail.MailMessage('%_mailFrom%', '%_mailTo%', '%_mailSubject%', '%_mailBody%');"
set "_mailCommand=%_mailCommand%$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath);"
set "_mailCommand=%_mailCommand%$SMTPMessage.Attachments.Add($attachment);"
set "_mailCommand=%_mailCommand%$SMTPClient = New-Object Net.Mail.SmtpClient('%_mailHost%', %_mailPort%);"
set "_mailCommand=%_mailCommand%$SMTPClient.EnableSsl = $true;"
set "_mailCommand=%_mailCommand%$SMTPClient.Credentials = New-Object System.Net.NetworkCredential('%_mailFrom%','%_mailSenderPassword%');"
set "_mailCommand=%_mailCommand%$SMTPClient.Send($SMTPMessage)}"
echo %_mailSenderPassword%
Unexpectedly I get an output like this:
12345Aa!
Exception calling "Send" with "1" argument(s): "Failure sending mail."
At line:1 char:499 ... m','12345Aa^');$SMTPClient.Send($SMTPMessage)}
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : SmtpException
As you can guess, my password is 12345Aa! and I defined it at the beginning of my code as set "_mailSenderPassword=12345Aa^^!"
So what am I missing? Thanks in advance!