.BAT FILE TO SEND EMAIL

This section contains scripts that hMailServer has contributed with. hMailServer 5 is needed to use these.
Post Reply
billyhughes_2015
New user
New user
Posts: 2
Joined: 2015-07-28 16:32
Location: Texas

.BAT FILE TO SEND EMAIL

Post by billyhughes_2015 » 2015-07-28 17:26

All,

I am running software that monitors various programs on pc to see if they are running properly. I would like to create a .bat file that will send a message from hmail, when this software calls the .bat file. I have tried with no success so far. Preferably a script that populates the email and sends it with no user interaction so that after hours I will get a notification if something is running correctly.

Hopefully this makes sense. :?:

Thank you,

User avatar
jimimaseye
Moderator
Moderator
Posts: 8170
Joined: 2011-09-08 17:48

Re: .BAT FILE TO SEND EMAIL

Post by jimimaseye » 2015-07-28 18:09

Use BLAT.EXE. I do. http://www.blat.net/

Usage:
blat.exe -mailfrom %emailFrom% -to %emailRecipient% -body "%body%" -subject "%subj%" -server localhost



Or you could go a bit more complicated and do your own script. This will get you started (CHECK IT and MODIFY IT YOURSELF before using for correct parameters etc):

VBSEmailer.vbs

Code: Select all

rem *  This script is a result of testing to create a method alternative to using Blat.exe
rem *
rem *  It needed to be able to calling to send an email whilst being unreliant/outside of hmailserver API.
rem *  In particular it was necessary to be able to attach a Text file (eg, Log file) that would
rem *  be attached to the sending emial and appear 'Inline' (as was possible with Blat).
rem *
rem * The conclusion is that this WORKS!  But it doesnt give anything more/better than what Blat does.  :-)
rem *  (It was just a proof of concept).
rem *
rem * It is CALLED by VBSEmailer.bat (which passes all the parameters)


SendFrom = WScript.Arguments.Named("SendFrom")
SendFromAddress = WScript.Arguments.Named("SendFromAddress")
SendSubject = WScript.Arguments.Named("SendSubject")
SendAddRecipient = WScript.Arguments.Named("SendAddRecipient")
SendBody = WScript.Arguments.Named("SendBody")
SendFile = WScript.Arguments.Named("SendFile")
Dim strLogFileName
strLogFileName = "C:\Users\Administrator\Documents\BatchFiles\emailer.log"
Set objFSO = CreateObject("Scripting.FileSystemObject")
if SendFile <> "" then
	SendFileTrim = objFSO.GetFileName(SendFile)
End If
if objFSO.FileExists(strLogFileName) Then
 Set myLog = objFSO.OpenTextFile(strLogFileName, 8 , True)
 Else
 Set myLog = objFSO.CreateTextFile(strLogFileName)
 End if
 
myLog.WriteLine now & " ------------Start of Session-----------------"
myLog.WriteLine "Sending " & SendFile & " to " & SendAddRecipient
myLog.WriteLine "Subject: " & SendSubject
myLog.WriteLine "From: " & SendFromAddress
myLog.WriteLine "Attached text file: " & SendFile

Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory.
Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network).

Const cdoAnonymous = 0 'Do not authenticate
Const cdoBasic = 1 'basic (clear-text) authentication
Const cdoNTLM = 2 'NTLM

Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = SendSubject
objMessage.From = SendFrom
objMessage.To = SendAddRecipient
objMessage.TextBody = SendBody

objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "192.168.0.200"  ' <-- your server hostname or IP address
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic
'Your UserID on the SMTP server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusername") = "sendinguser@yourdomain.com"
'Your password on the SMTP server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "secretpassword"
'Server port (typically 25)
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
'Use SSL for the connection (False or True)
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
objMessage.Configuration.Fields.Update

'==End remote SMTP server configuration section==

Dim iBp1
Dim iBp2

Set iBp1 = objMessage.BodyPart
Set Flds = iBp1.Fields
Flds("urn:schemas:mailheader:content-type") = "text/html"
Flds.Update

Set iBp2 = iBp1.AddBodyPart
With iBp2
   .ContentMediaType        = "text/plain"
   .ContentTransferEncoding = "quoted-printable"
   
   Set Flds = iBp2.Fields
   Flds("urn:schemas:mailheader:content-disposition") = "attachment; filename="""&SendFileTrim&""""
   Flds.Update
   Set Stm = .GetDecodedContentStream
   Stm.LoadFromFile SendFile
   Stm.Flush
End With

Stm.Close
Set Stm = Nothing
objMessage.Send
myLog.WriteLine now & " -------------End of Session------------------"
myLog.WriteLine "**********************************" 
myLog.Close


The above can be called with the following bat:

Code: Select all

echo off
cls
rem *  This script is a result of testing to create a method alternative to using Blat.exe
rem *
rem *  It needed to be able to calling to send an email whilst being unreliant/outside of hmailserver API.
rem *  In particular it was necessary to be able to attach a Text file (eg, Log file) that would
rem *  be attached to the sending emial and appear 'Inline' (as was possible with Blat).
rem *
rem * The conclusion is that this WORKS!  But it doesnt give anything more/better than what Blat does.  :-)
rem *  (It was just a proof of concept).
rem *
rem * It calls VBSEmailer.vbs to do the work (which also logs to Emailer.log)

set emailRecipient="defaultreceipient@yourdomain.com"
set /p "emailRecipient=Email Recipient [%emailRecipient%]--> "

set emailFrom="defaultsender@yourdomain.com"
set /p "emailFrom=Email FROM [%emailFrom%]--> "

set subj="TEST default subject"
set /p "subj=Subject: [%subj%]--> "
echo %subj%


set SendFile="d:\backups\Backup_2015-04-17-200000.log"
set /p "SendFile=Attachment [%SendFile%]--> "

set body=Here is some random body text.
set /p "body=Body Text: [%body%]--> "

cscript.exe //NoLogo VBSEmailer.vbs /SendFrom:%emailFrom% /SendFromAddress:%emailFrom% /SendAddRecipient:%emailRecipient% /SendSubject:"%subj%" /SendBody:"%body%" /SendFile:%SendFile%
Better still, go for BLAT. :-)


The above is offered to you as A CLUE on how you can acheive things but you will need to read, understand and adapt the methods to suit your monitoring processes.
HMS 5.6.6 B2383 on Win Server 2008 R2 Foundation, + 5.6.7-B2415 on test.
SpamassassinForWindows 3.4.0 spamd service
AV: Clamwin + Clamd service + sanesecurity defs : https://www.hmailserver.com/forum/viewtopic.php?f=21&t=26829

billyhughes_2015
New user
New user
Posts: 2
Joined: 2015-07-28 16:32
Location: Texas

Re: .BAT FILE TO SEND EMAIL

Post by billyhughes_2015 » 2015-07-28 18:14

Thank you jimimaseye for the quick response.

I'll give blat a try and let you know.

Thanks,

User avatar
jimimaseye
Moderator
Moderator
Posts: 8170
Joined: 2011-09-08 17:48

Re: .BAT FILE TO SEND EMAIL

Post by jimimaseye » 2015-07-28 19:25

Cheers
HMS 5.6.6 B2383 on Win Server 2008 R2 Foundation, + 5.6.7-B2415 on test.
SpamassassinForWindows 3.4.0 spamd service
AV: Clamwin + Clamd service + sanesecurity defs : https://www.hmailserver.com/forum/viewtopic.php?f=21&t=26829

alescan
Normal user
Normal user
Posts: 45
Joined: 2014-11-11 17:29
Location: Italy
Contact:

Re: .BAT FILE TO SEND EMAIL

Post by alescan » 2016-03-02 16:40

I don't know if you solved the problem but i post my solution anyway:
I use powershell function to send the email that is more simpler for me and call the script form a .bat

Here the powershell file mail.ps1

Code: Select all

Function Send-EMail {
    Param (
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailTo,
        [Parameter(`
            Mandatory=$true)]
        [String]$Subject,
        [Parameter(`
            Mandatory=$true)]
        [String]$Body,
        [Parameter(`
            Mandatory=$true)]
        
        [String]$Password
    )

		$EmailFrom = "user@domain"
        $SMTPServer = "HMAIL IP" 
        $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
        $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25) 
        $SMTPClient.EnableSsl = $true
        $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $Password); 
        $SMTPClient.Send($SMTPMessage)
        Remove-Variable -Name SMTPClient
        Remove-Variable -Name Password

} #End Function Send-EMail
Send-EMail -EmailTo "EMAIL@TO" -Body "YOUR MESSAGE" -Subject "YOUR SUBHECT" -password "accountFROMpsw"
the -password option is the password for the sender email account

and you call it from send.bat

Code: Select all

powershell.exe C:\Users\Administrator\Desktop\mail.ps1
Hope could be helpful
HMS 5.6.7 B2425 on Win Server 2016 Standard with SQL Server 2014 SP2

User avatar
jimimaseye
Moderator
Moderator
Posts: 8170
Joined: 2011-09-08 17:48

Re: .BAT FILE TO SEND EMAIL

Post by jimimaseye » 2016-03-02 19:27

Cheers Alescan, good for those that have powershell at their disposal. THat mean we have offered 3 options (VBS, a readymade EXE and powershell) now - variety is good.

Do you have a version that attaches files (and maybe also places them inline? (The VBS above does similar for guidance))
HMS 5.6.6 B2383 on Win Server 2008 R2 Foundation, + 5.6.7-B2415 on test.
SpamassassinForWindows 3.4.0 spamd service
AV: Clamwin + Clamd service + sanesecurity defs : https://www.hmailserver.com/forum/viewtopic.php?f=21&t=26829

alescan
Normal user
Normal user
Posts: 45
Joined: 2014-11-11 17:29
Location: Italy
Contact:

Re: .BAT FILE TO SEND EMAIL

Post by alescan » 2016-03-03 11:02

If you want to attach a file is very simple, on the las line you add the option -attachment

So it become

Code: Select all

Function Send-EMail {
    Param (
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailTo,
        [Parameter(`
            Mandatory=$true)]
        [String]$Subject,
        [Parameter(`
            Mandatory=$true)]
        [String]$Body,
        [Parameter(`
            Mandatory=$true)]
       
        [String]$Password
    )

        $EmailFrom = "user@domain"
        $SMTPServer = "HMAIL IP"
        $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
        $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
        $SMTPClient.EnableSsl = $true
        $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $Password);
        $SMTPClient.Send($SMTPMessage)
        Remove-Variable -Name SMTPClient
        Remove-Variable -Name Password
        $new_file="path to file"

} #End Function Send-EMail
Send-EMail -EmailTo "EMAIL@TO" -Body "YOUR MESSAGE" -Subject "YOUR SUBHECT" -password "accountFROMpsw" -attachment $new_file
HMS 5.6.7 B2425 on Win Server 2016 Standard with SQL Server 2014 SP2

User avatar
jimimaseye
Moderator
Moderator
Posts: 8170
Joined: 2011-09-08 17:48

Re: .BAT FILE TO SEND EMAIL

Post by jimimaseye » 2016-03-03 11:21

Do you have to edit that .PS1 script every time (to enter whatever 'sender', 'subject', 'body' 'attachment' etc) before you then call it with the BAT? Is there not a way to make it universal so the parameters can be entered at time of calling from the BAT ?
HMS 5.6.6 B2383 on Win Server 2008 R2 Foundation, + 5.6.7-B2415 on test.
SpamassassinForWindows 3.4.0 spamd service
AV: Clamwin + Clamd service + sanesecurity defs : https://www.hmailserver.com/forum/viewtopic.php?f=21&t=26829

Porngpisey
New user
New user
Posts: 1
Joined: 2017-03-14 08:44

Re: .BAT FILE TO SEND EMAIL

Post by Porngpisey » 2017-03-14 08:49

Hi alescan,

I just follow your instruction but i have a problem as in the attached file.

Do i have to configure the powershell.exe?

Best regards,
PS
Attachments
123.png

alescan
Normal user
Normal user
Posts: 45
Joined: 2014-11-11 17:29
Location: Italy
Contact:

Re: .BAT FILE TO SEND EMAIL

Post by alescan » 2017-03-14 09:32

Is a powershell security error, type this first (https://technet.microsoft.com/en-us/lib ... 76961.aspx):

Set-ExecutionPolicy Unrestricted

so you tell PS to run every script.
Now that you can run your script.
HMS 5.6.7 B2425 on Win Server 2016 Standard with SQL Server 2014 SP2

cusegrad1998
New user
New user
Posts: 4
Joined: 2017-08-30 23:21

Re: .BAT FILE TO SEND EMAIL

Post by cusegrad1998 » 2017-08-30 23:30

I tried doing the powershell script and am getting the following error. looks like a syntax error, but i copied exactly the code from before. Here's the error? any ideas?

Missing closing ')' in expression.
At C:\ibex\utils\extract\dailymail.ps1:7 char:13
+ <<<< Mandatory=$true)]
+ CategoryInfo : ParserError: (CloseParenToken:TokenId) [], Parse
Exception
+ FullyQualifiedErrorId : MissingEndParenthesisInExpression

Code I am using is below:

Function Send-EMail {
Param (
[Parameter('
Mandatory=$true)]
[String]$EmailTo,
[Parameter('
Mandatory=$true)]
[String]$Subject,
[Parameter('
Mandatory=$true)]
[String]$Body,
[Parameter('
Mandatory=$true)]

[String]$Password
)

$EmailFrom = "pturnbull@harriscomputer.com"
$SMTPServer = "mail.harriscomputer.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $Password);
$SMTPClient.Send($SMTPMessage)
Remove-Variable -Name SMTPClient
Remove-Variable -Name Password
$new_file="C:\ibex\utils\extract\Logs\DailyAuthReports.zip"

} #End Function Send-EMail
Send-EMail -EmailTo "xxxxx" -Body "This is your daily automated access logs delivery" -Subject "Daily Logs" -password "xxxxx" -attachment $new_file
Attachments
powershellerror.png
powershellerror.png (4.19 KiB) Viewed 39013 times

User avatar
jimimaseye
Moderator
Moderator
Posts: 8170
Joined: 2011-09-08 17:48

Re: .BAT FILE TO SEND EMAIL

Post by jimimaseye » 2017-08-30 23:41

I dont know about scripting in powershell but I note that your script uses standard apostrophes ' ' where as the original one uses back-apostrophes ` `

ie

yours:

Code: Select all

Function Send-EMail {
    Param (
        [Parameter('
            Mandatory=$true)]
        [String]$EmailTo,
        [Parameter('
            Mandatory=$true)]
Original from Alescan:

Code: Select all

Function Send-EMail {
    Param (
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailTo,
        [Parameter(`
            Mandatory=$true)]
Perhaps its them?
HMS 5.6.6 B2383 on Win Server 2008 R2 Foundation, + 5.6.7-B2415 on test.
SpamassassinForWindows 3.4.0 spamd service
AV: Clamwin + Clamd service + sanesecurity defs : https://www.hmailserver.com/forum/viewtopic.php?f=21&t=26829

tunis
Normal user
Normal user
Posts: 226
Joined: 2015-01-05 20:22
Location: Sweden

Re: .BAT FILE TO SEND EMAIL

Post by tunis » 2017-08-31 08:50

Your error says: MissingEndParenthesisInExpression
Why are end parenthesis missing?
You are missing apostrophes after $true.

Code: Select all

Function Send-EMail {
Param (
[Parameter('
Mandatory=$true')]
[String]$EmailTo,
[Parameter('
Mandatory=$true')]
[String]$Subject,
[Parameter('
Mandatory=$true')]
[String]$Body,
[Parameter('
Mandatory=$true')]
[String]$Password
)
HMS 5.6.8 B2437.17 on Windows Server 2019 Core VM.
HMS 5.6.8 B2451.21 on Windows Server 2016 Core VM.
HMS 5.6.7 B2425.16 on Windows Server 2012 R2 Core VM.

cusegrad1998
New user
New user
Posts: 4
Joined: 2017-08-30 23:21

Re: .BAT FILE TO SEND EMAIL

Post by cusegrad1998 » 2017-08-31 16:12

Thanks for the assistance. I'm nearly there. the ` was the first issue you helped solve, now it just can't find the named parameter -attachment. (and yes, i triple checked the mapped drive location to the attachment). Been staring at this for an hour now...

new error message = Send-EMail : A parameter cannot be found that matches parameter name 'attachment'.
At C:\ibex\utils\extract\dailymail.ps1:32 char:184


Here's the new code im using:

Function Send-EMail {
Param (
[Parameter(`
Mandatory=$true)]
[String]$EmailTo,
[Parameter(`
Mandatory=$true)]
[String]$Subject,
[Parameter(`
Mandatory=$true)]
[String]$Body,
[Parameter(`
Mandatory=$true)]
[String]$Password,
[Parameter(`
Mandatory=$true)]
[String]$new_file
)

$EmailFrom = "xxxxxx@harriscomputer.com"
$SMTPServer = "mail.xxxxx.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body,$new_file)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $Password);
$SMTPClient.Send($SMTPMessage)
Remove-Variable -Name SMTPClient
Remove-Variable -Name Password
$new_file="C:\ibex\utils\extract\Logs\DailyAuthLog.xls"

} #End
Send-EMail -EmailTo "xxxxxxx" -Body "This is your daily automated eRx access logs delivery" -Subject "Daily eRx Logs" -password "xxxxx" -attachment $new_file

tunis
Normal user
Normal user
Posts: 226
Joined: 2015-01-05 20:22
Location: Sweden

Re: .BAT FILE TO SEND EMAIL

Post by tunis » 2017-08-31 16:59

cusegrad1998 wrote:new error message = Send-EMail : A parameter cannot be found that matches parameter name 'attachment'.
At C:\ibex\utils\extract\dailymail.ps1:32 char:184
In your script the parameter name is new_file, also you have declared $new_file in the end off the function.

Try this

Code: Select all

Function Send-EMail {
Param (
[Parameter(`
Mandatory=$true)]
[String]$EmailTo,
[Parameter(`
Mandatory=$true)]
[String]$Subject,
[Parameter(`
Mandatory=$true)]
[String]$Body,
[Parameter(`
Mandatory=$true)]
[String]$Password,
[Parameter(`
Mandatory=$true)]
[String]$Attachment
)

$EmailFrom = "xxxxxx@harriscomputer.com"
$SMTPServer = "mail.xxxxx.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body,$Attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $Password);
$SMTPClient.Send($SMTPMessage)
Remove-Variable -Name SMTPClient
Remove-Variable -Name Password

} #End
Send-EMail -EmailTo "xxxxxxx" -Body "This is your daily automated eRx access logs delivery" -Subject "Daily eRx Logs" -Password "xxxxx" -Attachment "C:\ibex\utils\extract\Logs\DailyAuthLog.xls"
HMS 5.6.8 B2437.17 on Windows Server 2019 Core VM.
HMS 5.6.8 B2451.21 on Windows Server 2016 Core VM.
HMS 5.6.7 B2425.16 on Windows Server 2012 R2 Core VM.

cusegrad1998
New user
New user
Posts: 4
Joined: 2017-08-30 23:21

Re: .BAT FILE TO SEND EMAIL

Post by cusegrad1998 » 2017-08-31 22:34

So, I was finally able to get this thing to work. had to add a few lines of code to actually "add" the referenced attachment to the SMTP call. Final code that is working looks like this.
I highlighted the lines of code I added. Thanks for all the help!

Function Send-EMail {
Param (
[Parameter(`
Mandatory=$true)]
[String]$EmailTo,
[Parameter(`
Mandatory=$true)]
[String]$Subject,
[Parameter(`
Mandatory=$true)]
[String]$Body,
[Parameter(`
Mandatory=$true)]
[String]$Password,
[Parameter(`
Mandatory=$true)]
[String]$Attachment
)

$EmailFrom = "xxxx@xxxx"
$SMTPServer = "xxxx.xxxx.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$Att = New-Object System.Net.Mail.Attachment($Attachment)
$SMTPMessage.Attachments.add($Att)

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $Password);
$SMTPClient.Send($SMTPMessage)
Remove-Variable -Name SMTPClient
Remove-Variable -Name Password

} #End
Send-EMail -EmailTo "xxxx@xxx.com" -Body "This is your daily automated eRx access logs delivery" -Subject "Daily eRx Logs" -Password "xxxxxxx" -Attachment "C:\ibex\utils\extract\Logs\DailyAuthReports.zip"

User avatar
mattg
Moderator
Moderator
Posts: 20284
Joined: 2007-06-14 05:12
Location: 'The Outback' Australia

Re: .BAT FILE TO SEND EMAIL

Post by mattg » 2017-09-01 01:00

Just noticed the eRX....

You are from my world, Aussie Healthcare..
Just 'cause I link to a page and say little else doesn't mean I am not being nice.
https://www.hmailserver.com/documentation

cusegrad1998
New user
New user
Posts: 4
Joined: 2017-08-30 23:21

Re: .BAT FILE TO SEND EMAIL

Post by cusegrad1998 » 2017-09-01 01:15

Mattg, I feel your pain. :x

Post Reply