I'm running Windows 2003 Service Pack 2. I have a batch file that runs on demand. I want to have an email sent every time the batch file runs. The email is simple, just a sentence indicating that the batch file ran; it is the same every time.
I've tried a couple of things to get this done. I thought of telnet, but I can't figure out how to redirect a set of commands into telnet; Windows batch files don't have a Unix-style "here document," and calling "telnet <scriptfile" where scriptfile contains the commands to send an email didn't work. I also found a couple of solutions on the internet using CDO.Message, but I've never used that before and I kept getting error messages that I don't understand.
How can I send a simple email from a Windows batch file?
Max is on he right track with the suggestion to use Windows Scripting for a way to do it without installing any additional executables on the machine. His code will work if you have the IIS SMTP service setup to forward outbound email using the "smart host" setting, or the machine also happens to be running Microsoft Exchange. Otherwise if this is not configured, you will find your emails just piling up in the message queue folder (\inetpub\mailroot\queue). So, unless you can configure this service, you also want to be able to specify the email server you want to use to send the message with. To do that, you can do something like this in your windows script file:
Set objMail = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
'uncomment next three lines if you need to use SMTP Authorization
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Update
objMail.Configuration = objConf
objMail.FromName = "Your Name"
objMail.From = "your#address.com"
objMail.To = "destination#address.com"
objMail.Subject = "Email Subject Text"
objMail.TextBody = "The message of the email..."
objMail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing
I've used Blat ( http://www.blat.net/ ) for many years.
It's a simple command line utility that can send email from command line.
It's free and opensource.
You can use command like "Blat myfile.txt -to fee#fi.com -server smtp.domain.com -port 6000"
Here is some other software you can try to send email from command line (I've never used them):
http://caspian.dotconf.net/menu/Software/SendEmail/
http://www.petri.co.il/sendmail.htm
http://www.petri.co.il/software/mailsend105.zip
http://retired.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm
Here ( http://www.petri.co.il/send_mail_from_script.htm ) you can find other various way of sending email from a VBS script, plus link to some of the mentioned software
The following VBScript code is taken from that page
Set objEmail = CreateObject("CDO.Message")
objEmail.From = "me#mydomain.com"
objEmail.To = "you#yourdomain.com"
objEmail.Subject = "Server is down!"
objEmail.Textbody = "Server100 is no longer accessible over the network."
objEmail.Send
Save the file as something.vbs
Set Msg = CreateObject("CDO.Message")
With Msg
.To = "you#yourdomain.com"
.From = "me#mydomain.com"
.Subject = "Hello"
.TextBody = "Just wanted to say hi."
.Send
End With
Save the file as something2.vbs
I think these VBS scripts use the windows default mail server, if present.
I've not tested these scripts...
If PowerShell is available, the Send-MailMessage commandlet is a single one-line command that could easily be called from a batch file to handle email notifications. Below is a sample of the line you would include in your batch file to call the PowerShell script (the %xVariable% is a variable you might want to pass from your batch file to the PowerShell script):
--[BATCH FILE]--
:: ...your code here...
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -windowstyle hidden -command C:\MyScripts\EmailScript.ps1 %xVariable%
Below is an example of what you might include in your PowerShell script (you must include the PARAM line as the first non-remark line in your script if you included passing the %xVariable% from your batch file:
--[POWERSHELL SCRIPT]--
Param([String]$xVariable)
# ...your code here...
$smtp = "smtp.[emaildomain].com"
$to = "[Send to email address]"
$from = "[From email address]"
$subject = "[Subject]"
$body = "[Text you want to include----the <br> is a line feed: <br> <br>]"
$body += "[This could be a second line of text]" + "<br> "
$attachment="[file name if you would like to include an attachment]"
send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Attachment $attachment -Priority high
If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.
I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.
A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.
$emailSmtpServerPort = "587"
$emailSmtpUser = "username"
$emailSmtpPass = 'password'
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "[From email address]"
$emailMessage.To.Add( "[Send to email address]" )
$emailMessage.Subject = "Testing e-mail"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = #"
<p>Here is a message that is <strong>HTML formatted</strong>.</p>
<p>From your friendly neighborhood IT guy</p>
"#
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )
It works for me, by using double quotes around variables.
I am using batch script to call powershell Send-MailMessage
Batch Script:send_email.bat
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command 'E:\path\send_email.ps1
Pwershell Script send_email.ps1
Send-MailMessage -From "noreply#$env:computername" -To '<target_email#example.com>' -Subject 'Blah Blah' -SmtpServer 'smtp.domain.com' -Attachments 'E:\path\file.log' -BODY "Blah Blah on Host: $env:computername "
I struggled with the same problem and finally found a simple soultion. I know I am late to answer this question. But still writing if it can help someone like me who is searching for it.
You can send simple mail using Powershell script. Make sure to connect this in your bat file
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "hi#company.com"
$Mail.Subject = "hello"
$Mail.Body ="Hello. I am here to wish you"
$Mail.Send()
Using this, you need not use any other party apps or install anything extra. It just needs Outlook. I hope that will be already there in many office accounts.
This post helped me
Send E-Mail using powershell
Related
I would like to execute some command then send them into my web server for analysis.
somethink like :
wmic csproduct get | wget http://someserver/cgi-bin/hello.pl
Except that wget is not delivered out-of-the-box by Microsoft.
How can I make the same using stuff that are delivered with Windows 2000 and futher? Can vbscript do the job?
Since you executing some commands to get your information, may be it would be more native to use a command shell environment?
How about PowerShell?
(New-Object System.Net.WebClient).UploadString("http://someserver/cgi-bin/hello.pl", (Get-WMIObject Win32_BIOS) )
read about the UploadString() method here
If you still want to stick to a vbscript solution, here is a sample code which accepts a text from stdin and posts it to your server:
Dim inp, http_req
inp = inp & WScript.StdIn.ReadAll()
WScript.Echo "Input: " & inp
Set http_req = CreateObject("WinHTTP.WinHTTPRequest.5.1")
http_req.open "POST", "http://someserver/cgi-bin/hello.pl", false
http_req.setRequestHeader "Content-Type", "text/plain"
http_req.send inp
The minimum requirements seems to be Windows 2000 Professional with SP3 , i personnaly tested the script with Windows XP.
I have a powershell script that is searching the Windows Search index directly for emails and files. I have the following code:
$searchme="my thing to find"
$sql="SELECT System.FileName, System.ItemPathDisplay, System.DateCreated, System.DateModified, system.itemurl, system.itemtypetext FROM SYSTEMINDEX WHERE Contains(System.FileName, '"+$searchme+"') OR Contains('"+$searchme+"')"
$adapter = new-object system.data.oledb.oleDBDataadapter -argumentlist $sql, "Provider=Search.CollatorDSO;Extended Properties=’Application=Windows’;"
$ds = new-object system.data.dataset
$adapter.Fill($ds)
foreach ($record in $ds.Tables[0].Rows)
{
$exeparams = $record[4]
write-host $exeparams
write-host $exeparams.split(":")[0]
if ($exeparams.split(":")[0] -eq "mapi15")
{
$exeparams2="mapi://" + $exeparams.substring(8)
}
write-host $exeparams
write-host "start"
$exe="start"
$exe+" "+$exeparams | Out-File 'file.txt' -encoding Unicode
write-host "start-process"
Start-Process $exeparams
Start-Process $exeparams2
write-host "andpersand process"
&$exe $exeparams
&$exe $exeparams2
write-host "dotnet"
$proc = [Diagnostics.Process]::Start($exeparams)
$proc.WaitForExit()
$proc = [Diagnostics.Process]::Start($exeparams2)
$proc.WaitForExit()
}
There are several "shell" calls because I was trying to figure out if it was a process spawning issue. Files work with no issue. Emails however fail with either No such interface if i leave mapi15, or Unspecified error if i change mapi15 to mapi. I believe that Open mails in outlook from java using the protocol "mapi://" may be the solution, but if it is I am not sure how to apply this in powershell. Thank you for your help.
Ok, that took more work than I expected, and I blame Office 2013 for it. Here's the short answer:
$exeparams2 = $exeparams -replace "^mapi15", "mapi"
& start $exeparams2
That is the code that now opens an email for me. That code did not do that yesterday, all it did is tell me:
Either there is no default mail client or the current mail client cannot fulfill the messaging request. Please run Microsoft Outlook and set it as the default mail client.
Infuriating is what this was, because I did have Outlook, in fact it was running, and was the default mail application for everything email related. This annoyed me, and sent me on a quest to figure out WTF was wrong, and if I could fix it. The answers to that are "I'm not real sure WTF was wrong, except maybe a naming change on MS's part", and "yes, yes I can fix it".
I finally found the fix that worked for me (and I believe that this is probably Office 2013/Office 365 specific) was found at the bottom of this thread:
https://social.technet.microsoft.com/Forums/office/en-US/64c0bedf-2bcd-40aa-bb9c-ad5de20c84be/cannot-send-email-with-microsoft-outlook-2010-64-bit-from-adobe-outlook-not-recognised-as?forum=outlook
The process is simple. Change 2 Registry Entries, then re-set your default mail application. Registry entries:
HKLM:\Software\Clients\Mail(default)
HKLM:\Software\Clients\Mail\Microsoft Outlook(default)
Change the value of (Default) from "Microsoft Outlook" to simply "Outlook".
After that I set Outlook to be the default for everything it could be ( in Win8 that's Control Panel > All Control Panel Items > Default Programs > Set Default Programs then select Outlook, and choose the first option to make it default for all extensions that it is registered for). Once that was done I was able to run the modified code above to launch an email that I had search the index for.
I have a Vb script which calls a bat file.the bat file contans logic to send email.i run the bat file using objShell.run.when i give an invalid email server name in the bat file.the email is not sent.But objShell.run always returns a 0.How to do exception handling in this case.please help
If you are using the objShell.run method it is running a separately process and do not care about the current process you are running. I would look at the ProcessStartInfo. I think you can redirect the input/output/error stream from the ProcessStartInfo. Here and here are some link about it
Your best bet would be to use CDO to send your email right from the VBScript. Otherwise, error handling in Batch is extremely difficult and you will have to resort to exit codes.
If you want to send without installation then try the second method. you have to initialize the objects. In that example i remove h in the link because i can't post links
CDO.MESSAGE
'Script to send an email through QTP nice one Set oMessage = CreateObject("CDO.Message")
'==This section provides the configuration information for the remote SMTP server. '==Normally you will only change the server name or IP. oMessage.Configuration.Fields.Item _ ("ttp://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Name or IP of Remote SMTP Server oMessage.Configuration.Fields.Item _ ("ttp://schemas.microsoft.com/cdo/configuration/smtpserver") =""
'Server port (typically 25) oMessage.Configuration.Fields.Item _ ("ttp://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
oMessage.Configuration.Fields.Update oMessage.Subject = "Test Mail" oMessage.Sender = "" oMessage.To ="" 'oMessage.CC = "" 'oMessage.BCC = "" oMessage.TextBody = "Test Mail from QTP"&vbcrlf&"Regards,"&vbcrlf&"Test" oMessage.Send
Set oMessage = Nothing
I'm running Windows 2003 Service Pack 2. I have a batch file that runs on demand. I want to have an email sent every time the batch file runs. The email is simple, just a sentence indicating that the batch file ran; it is the same every time.
I've tried a couple of things to get this done. I thought of telnet, but I can't figure out how to redirect a set of commands into telnet; Windows batch files don't have a Unix-style "here document," and calling "telnet <scriptfile" where scriptfile contains the commands to send an email didn't work. I also found a couple of solutions on the internet using CDO.Message, but I've never used that before and I kept getting error messages that I don't understand.
How can I send a simple email from a Windows batch file?
Max is on he right track with the suggestion to use Windows Scripting for a way to do it without installing any additional executables on the machine. His code will work if you have the IIS SMTP service setup to forward outbound email using the "smart host" setting, or the machine also happens to be running Microsoft Exchange. Otherwise if this is not configured, you will find your emails just piling up in the message queue folder (\inetpub\mailroot\queue). So, unless you can configure this service, you also want to be able to specify the email server you want to use to send the message with. To do that, you can do something like this in your windows script file:
Set objMail = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
'uncomment next three lines if you need to use SMTP Authorization
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Update
objMail.Configuration = objConf
objMail.FromName = "Your Name"
objMail.From = "your#address.com"
objMail.To = "destination#address.com"
objMail.Subject = "Email Subject Text"
objMail.TextBody = "The message of the email..."
objMail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing
I've used Blat ( http://www.blat.net/ ) for many years.
It's a simple command line utility that can send email from command line.
It's free and opensource.
You can use command like "Blat myfile.txt -to fee#fi.com -server smtp.domain.com -port 6000"
Here is some other software you can try to send email from command line (I've never used them):
http://caspian.dotconf.net/menu/Software/SendEmail/
http://www.petri.co.il/sendmail.htm
http://www.petri.co.il/software/mailsend105.zip
http://retired.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm
Here ( http://www.petri.co.il/send_mail_from_script.htm ) you can find other various way of sending email from a VBS script, plus link to some of the mentioned software
The following VBScript code is taken from that page
Set objEmail = CreateObject("CDO.Message")
objEmail.From = "me#mydomain.com"
objEmail.To = "you#yourdomain.com"
objEmail.Subject = "Server is down!"
objEmail.Textbody = "Server100 is no longer accessible over the network."
objEmail.Send
Save the file as something.vbs
Set Msg = CreateObject("CDO.Message")
With Msg
.To = "you#yourdomain.com"
.From = "me#mydomain.com"
.Subject = "Hello"
.TextBody = "Just wanted to say hi."
.Send
End With
Save the file as something2.vbs
I think these VBS scripts use the windows default mail server, if present.
I've not tested these scripts...
If PowerShell is available, the Send-MailMessage commandlet is a single one-line command that could easily be called from a batch file to handle email notifications. Below is a sample of the line you would include in your batch file to call the PowerShell script (the %xVariable% is a variable you might want to pass from your batch file to the PowerShell script):
--[BATCH FILE]--
:: ...your code here...
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -windowstyle hidden -command C:\MyScripts\EmailScript.ps1 %xVariable%
Below is an example of what you might include in your PowerShell script (you must include the PARAM line as the first non-remark line in your script if you included passing the %xVariable% from your batch file:
--[POWERSHELL SCRIPT]--
Param([String]$xVariable)
# ...your code here...
$smtp = "smtp.[emaildomain].com"
$to = "[Send to email address]"
$from = "[From email address]"
$subject = "[Subject]"
$body = "[Text you want to include----the <br> is a line feed: <br> <br>]"
$body += "[This could be a second line of text]" + "<br> "
$attachment="[file name if you would like to include an attachment]"
send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Attachment $attachment -Priority high
If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.
I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.
A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.
$emailSmtpServerPort = "587"
$emailSmtpUser = "username"
$emailSmtpPass = 'password'
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "[From email address]"
$emailMessage.To.Add( "[Send to email address]" )
$emailMessage.Subject = "Testing e-mail"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = #"
<p>Here is a message that is <strong>HTML formatted</strong>.</p>
<p>From your friendly neighborhood IT guy</p>
"#
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )
It works for me, by using double quotes around variables.
I am using batch script to call powershell Send-MailMessage
Batch Script:send_email.bat
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command 'E:\path\send_email.ps1
Pwershell Script send_email.ps1
Send-MailMessage -From "noreply#$env:computername" -To '<target_email#example.com>' -Subject 'Blah Blah' -SmtpServer 'smtp.domain.com' -Attachments 'E:\path\file.log' -BODY "Blah Blah on Host: $env:computername "
I struggled with the same problem and finally found a simple soultion. I know I am late to answer this question. But still writing if it can help someone like me who is searching for it.
You can send simple mail using Powershell script. Make sure to connect this in your bat file
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "hi#company.com"
$Mail.Subject = "hello"
$Mail.Body ="Hello. I am here to wish you"
$Mail.Send()
Using this, you need not use any other party apps or install anything extra. It just needs Outlook. I hope that will be already there in many office accounts.
This post helped me
Send E-Mail using powershell
I would like to send mail from a script on a Windows Server 2003 Standard Edition. I think the server setup is pretty much out of the box.
The mail server is an Exchange one, and when you're on the internal network you can use plain old SMTP. I have done it from my machine with Perl, but unfortunately Perl is not available on the server.
Is there an easy way of doing this from a .bat-file or any other way that doesn't require installing some additional software?
Edit:
Thanks for the quick replies. The "blat" thingie would probably work fine but with wscript I don't have to use a separate binary.
I didn't see PhiLho's post the first time I edited and selected an answer. No need for me to duplicate the code here.
Just save the script to a file, say sendmail.vbs, and then call it from the command prompt like so:
wscript sendmail.vbs
It is possible with Wscript, using CDO:
Dim objMail
Set objMail = CreateObject("CDO.Message")
objMail.From = "Me <Me#Server.com>"
objMail.To = "You <You#AnotherServer.com>"
objMail.Subject = "That's a mail"
objMail.Textbody = "Hello World"
objMail.AddAttachment "C:\someFile.ext"
---8<----- You don't need this part if you have an active Outlook [Express] account -----
' Use an SMTP server
objMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
' Name or IP of Remote SMTP Server
objMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"smtp.server.com"
' Server port (typically 25)
objMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMail.Configuration.Fields.Update
----- End of SMTP usage ----->8---
objMail.Send
Set objMail=Nothing
Wscript.Quit
Update: found more info there: VBScript To Send Email Using CDO
By default it seems it uses Outlook [Express], so it didn't worked on my computer but you can use a given SMTP server, which worked fine for me.
If the server happened (I realize how old this question is) to have Powershell v2 installed, the CmdLet Send-MailMessage would do this in one line.
Send-MailMessage [-To] <string[]> [-Subject] <string> -From <string> [[-Body] <string>] [[-SmtpServer] <string>] [-Attachments <string[]>] [-Bcc <string[]>] [-BodyAsHtml] [-Cc <string[]>] [-Credential <PSCredential>] [-DeliveryNotficationOption {None | OnSuccess | OnFailure | Delay | Never}] [-Encoding <Encoding>] [-Priority {Normal | Low | High}] [-UseSsl] [<CommonParameters>]
I don't know if dropping a binary alongside the .bat file counts as installing software, but, if not, you can use blat to do this.
If you have outlook/exchange installed you should be able to use CDONTs, just create a mail.vbs file and call it in a batch file like so (amusing they are in the same dir)
wscript mail.vbs
for the VBScript code check out
http://support.microsoft.com/kb/197920
http://www.w3schools.com/asp/asp_send_email.asp
forget the fact they the two links speak about ASP, it should work fine as a stand alone script with out iis.
I think that you'll have to install some ActiveX or other component what could be invoked from WScript, such as:
http://www.activexperts.com/ActivEmail/
and:
http://www.emailarchitect.net/webapp/SMTPCOM/developers/scripting.asp
Otherwise, you'll have to write the entire SMTP logic (if possible, not sure) in WScript all on your own.
Use CDONTS with Windows Scripting Host (WScript)
Is there a way you send without referencing the outside schema urls.
http://schemas.microsoft.com/cdo/configuration/
That is highly useless as it can't be assumed all boxes will have outside internet access to send mail internally on the local exchange. Is there a way to save the info from those urls locally?