Command line email script to send a file found in a folder

NewFile1 folder occasionally has a text file written into it, just 1 file.
The file gets occasionally deleted, and a new one is written into it from time to time.

I need a script which will look in the NewFile1 Folder, and if it sees a file in there, to send it via email, and attach it to the email.  It will always send it to the same email address.

This needs to work in a .bat file as it will be an addition to an existing script.

If the script runs and there NewFile1 folder is empty, then of course it would not need to send any email out.

This script should work on Windows 7 and Windows Server 2008 in an Exchange 2010 environment.
100questionsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Giovanni HewardCommented:
Try blat...

Here's a demo script::

@echo off
setlocal enabledelayedexpansion
cd /d "%~dp0"
if not exist blat.exe (
	echo Requires http://sourceforge.net/projects/blat/files/
	goto :eof
)
set recipient="group@domain.com"
set server=127.0.0.1:25
set sender="<user@domain.com>"
set username="user"
set password="password"
set file="%temp%\example.txt"

if exist !file! call :sendfile
goto :eof

:sendfile

blat -to !recipient! -subject "Subject" -body "Body Message." -server !server! -f !sender! -u !username! -pw !password! -debug -attach !file!

Open in new window

0
Steven CarnahanNetwork ManagerCommented:
You should also be able to use powershell.  

In batch file (borrowed from x66_x72_x65_x65 above :) ):

set file="%temp%\example.txt"

if exist !file! %windir%\system32\windowspowershell\v1.0\powershell.exe smailnow.ps1



Save this script as smailnow.ps1 after making changes you want/need.

$smtp = new-object Net.Mail.SmtpClient("mail.example.com")

if( $Env:SmtpUseCredentials -eq "true" ) {
    $credentials = new-object Net.NetworkCredential("username","password")
    $smtp.Credentials = $credentials
}
$objMailMessage = New-Object System.Net.Mail.MailMessage
$objMailMessage.From = "script@mycompany.com"
$objMailMessage.To.Add("you@yourcompany.com")
$objMailMessage.Subject = "eMail subject Notification"
$objMailMessage.Body = "Hello world!"

$smtp.send($objMailMessage)

Open in new window

0
100questionsAuthor Commented:
Thank you. Would this also work if the server address looks something like this:  name.name.local?  If I want to use SSL will this also work?
0
10 Tips to Protect Your Business from Ransomware

Did you know that ransomware is the most widespread, destructive malware in the world today? It accounts for 39% of all security breaches, with ransomware gangsters projected to make $11.5B in profits from online extortion by 2019.

100questionsAuthor Commented:
Thanks pony10us.  Would I have to use an smtp server address for this or could i used a .local address as well?
0
100questionsAuthor Commented:
pony10us, also the file that I want to attach does not always have the same name, can I also use a *.txt for instance or do I need the same file name all the time?
0
Steven CarnahanNetwork ManagerCommented:
I think you have to use smtp.

I did leave out the attachment portion. Having a little trouble getting that part working yet.
0
100questionsAuthor Commented:
x66_x72_x65_x65 - thank you for the script.  Would your script work with a .local server name as well?
0
Steven CarnahanNetwork ManagerCommented:
Here is what I have:

$emailattachment = "c:\user\test\mytesta.txt"
$att = new-object Net.Mail.Attachment($emailattachment)

$smtp = new-object Net.Mail.SmtpClient("server or IP")

if( $Env:SmtpUseCredentials -eq "true" ) {
    $credentials = new-object Net.NetworkCredential("domain\user","password")
    $smtp.Credentials = $credentials
}
$objMailMessage = New-Object System.Net.Mail.MailMessage
$objMailMessage.From = "script@mycompany.com"
$objMailMessage.To.Add("me@mycompany.com")
$objMailMessage.Subject = "eMail subject Notification"
$objMailMessage.Body = "Hello world!"
$mailmessage.Attachments.Add($att)

$smtp.send($objMailMessage)

Open in new window


However I am getting an error on this line:

$mailmessage.Attachments.Add($att)

"You cannot call a method on a null-valued expression."

The file exists.  I have an appointment so I can't work on it until tomorrow now. perhaps someone else can jump in here?

***   It is sending the email but not the attachment  ***
***  I did use a local server name and it worked ***
0
Giovanni HewardCommented:
It's all a matter of name resolution.  If the machine your running this on can properly resolve .local addresses then you'll be fine.  This generally means your DNS servers are configured to point to the local DNS server(s) for the domain, or you have a static entry in your %windir%\system32\drivers\etc\hosts file.

ping server.domain.local to verify.


To use blat with TLS/SSL, you'll need to also configure STUNNEL... not to complicate things. :)
0
100questionsAuthor Commented:
x66_x72_x65_x65 - Thanks again.  To clarify a few things about your script, will your script allow me to send the file which is found in the NewFile1 folder?  The file does not always hae the same name, however it has the same extension.  For instance if it's always a .txt file, how can I modify your script so that it will send the .txt file it find in NewFile1 folder?
0
Giovanni HewardCommented:
This would do it...

@echo off
setlocal enabledelayedexpansion
cd /d "%~dp0"
if not exist blat.exe (
	echo Requires http://sourceforge.net/projects/blat/files/
	goto :eof
)
set recipient="group@domain.com"
set server=127.0.0.1:25
set sender="<user@domain.com>"
set username="user"
set password="password"

for /f "delims=" %%f in ('dir *.txt /s/a-d/b') do (
 call :sendfile "%%f"
)
goto :eof

:sendfile
blat -to !recipient! -subject "Subject" -body "Body Message." -server !server! -f !sender! -u !username! -pw !password! -debug -attach "!file!"

Open in new window

0
Steven CarnahanNetwork ManagerCommented:
Okay, I have re-written the powershell script and tested it out.  I am making a couple of assumptions:

1.  NewFile1 is at the root of C:\
2. I included the CC field for example.

Here is the ps1 file:

$SourceDir = "c:\NewFile1\*.*"

   $Message = @{
      From=”Reporting@domain.com ”
      To=”who@domain.com“
      CC=”whoelse@domain.com”
      Subject= “subject”
      SmtpServer= "<server name or ip>”
      Body = “subject”
    }

Send-MailMessage @Message -Attachments @(Get-ChildItem $SourceDir | foreach{$_.fullname})

Open in new window


This will take any file that is in the C:\NewFile1 folder and send as an attachment in an email.
0
Giovanni HewardCommented:
@pony10us -- does this work with TLS/SSL?
0
Steven CarnahanNetwork ManagerCommented:
Now that's a good question.  The way I have it written I don't think so.  Another assumption on my part was that the files would be sent internally and would not require SSL.

I am unable to test this as my system does not support secure connections however when I add the lines:

UseSsl = $true
Credential = "gmail address"

as well as set the SMTP server to smtp.gmail.com

just before the From line and run it I am prompted for a password.

I am unable to to complete the test beyond that at this time.
0
100questionsAuthor Commented:
@pony10us -- when you specifyt the smtp server do you also have to specify the port?
0
100questionsAuthor Commented:
x66_x72_x65_x65 -- I tried your script however I get an error message:  
- attach <file> - :attach binary file(s) to message (filenames comma spearated)

Also, how do I specify where it needs to look in which directory to find the file it needs to attach?

Thanks.
0
Giovanni HewardCommented:
Will there be more than one file at a time, or just a randomly named single file?

The path is specified in the area bolded below ( script has been corrected ) :

@echo off
setlocal enabledelayedexpansion
cd /d "%~dp0"
if not exist blat.exe (
      echo Requires http://sourceforge.net/projects/blat/files/
      goto :eof
)
set recipient="group@domain.com"
set server=127.0.0.1:25
set sender="<user@domain.com>"
set username="user"
set password="password"

for /f "delims=" %%f in ('dir x:\path\*.txt /s/a-d/b') do (
 call :sendfile "%%f"
)
goto :eof

:sendfile
echo Sending file: %1
blat -to !recipient! -subject "Subject" -body "Body Message." -server !server! -f !sender! -u !username! -pw !password! -debug -attach "%~1"
0
Steven CarnahanNetwork ManagerCommented:
Another good point.  I see that gmail uses port 587 (not the standard port 25) so I did some checking.  As near as I can tell it really depends on the version of Powershell you are running.  If you are using version 3 then you can set the port simply by placing the following line:

Port = 587 in the code I provided above. If you are using version 2 or earlier I find lots of attempts but Powershell magazine (where I found out about the port option) states that there is not a way to specify a port.

Here is a link to the article that I got this information from:  http://www.powershellmagazine.com/2012/10/25/pstip-sending-emails-using-your-gmail-account/

I am running 2.0 which is why it doesn't work for me.  Perhaps I should upgrade.  :)
0
Giovanni HewardCommented:
OK, this is tested as working...  modify the set loc=c:\temp\*.txt value as needed.

@echo off
setlocal enabledelayedexpansion
cd /d "%~dp0"
if not exist blat.exe (
      echo Requires http://sourceforge.net/projects/blat/files/
      goto :eof
)
set recipient="group@domain.com"
set server=127.0.0.1:25
set sender="<user@domain.com>"
set username=user
set password=password
set subject=Subject
set body=Body Message.
set loc=c:\temp\*.txt
set log=%~n0.log

echo Searching !loc! please wait...
for /f "delims=" %%f in ('dir !loc! /s/a-d/b') do (
	call :sendfile "%%f"
)
if exist !log! type !log!
goto :eof

:sendfile
if exist %1 (
	echo Sending file: %~1
	blat -to !recipient! -subject "!subject!" -body "!body!" -server !server! -f !sender! -u "!username!" -pw "!password!" -debug -attach "%~1">>!log! 2>&1
)

Open in new window

0
100questionsAuthor Commented:
x66_x72_x65_x65 -- Thanks.  Is the command you list "cd /d "%~dp0" somehow telling the script where blat is located, that is in drive d?
0
100questionsAuthor Commented:
x66_x72_x65_x65 --
The above script seems to work however only after I remove the following:

if not exist blat.exe (
      echo Requires http://sourceforge.net/projects/blat/files/
      goto :eof
)

Is there a need for this to be in the script?  It seems to be hindering for the script to work properly?
0
Giovanni HewardCommented:
"cd /d "%~dp0" changes to the location where the script actually resides.  By default, it looks for blat in the same folder.  So long as blat resides in your %path%, you are fine to remove both sections.
0
100questionsAuthor Commented:
x66_x72_x65_x65 --

To confirm, it is ok to remove the following as long as the script resides in my %path% ?
cd /d "%~dp0"
if not exist blat.exe (
      echo Requires http://sourceforge.net/projects/blat/files/
      goto :eof
)
0
Giovanni HewardCommented:
Yes, so long at blat.exe resides in your %path%; the script itself can reside outside of your %path%, so long as it's started directly (via Task Scheduler for example)
0
Steven CarnahanNetwork ManagerCommented:
x66_x72_x65_x65:  Very good script and it appears that the author is capable of using Blat so I recommend that path in this case.  

What I was providing was a script for those that may not be permitted to use a third party program such as blat.exe, no matter how much it makes life easier :).  Unfortunately, there are some "gotcha's" in my method that I would have to really work on to find a solution to.
0
100questionsAuthor Commented:
I've requested that this question be closed as follows:

Accepted answer: 0 points for 100questions's comment #a39489084

for the following reason:

I had to remove part of the script.
0
Giovanni HewardCommented:
Full points should be awarded as final script ( ID: 39488557 ) worked without modification (if blat.exe was placed in same folder as script, as designed.)  Even with slight script modification essential elements were provided.  Experts should not be penalized for authors lack of understanding.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
100questionsAuthor Commented:
@x66_x72_x65_x65 --  I do lack understanding, 0 points is not what is merited for your script, my omission.  I will revise and submit, however one last inquiry please,
I removed the 4 blat files from the same directory as the script, however the part of the script which follows:

if not exist blat.exe (
      echo Requires http://sourceforge.net/projects/blat/files/
      goto :eof
)

does not seem to have any effect when I run the script.  I do not see a message which would inform the user of the script that they need blat to run the script.  Can this small modification be made to your script?  Thanks.
0
100questionsAuthor Commented:
@x66_x72_x65_x65 -- I have one further request please.  I tried this on another server and the log in part shows the following.  I have replaced the email address for privacy.
The email server address spelled correctly.  The sender name is accurate as well.

>>>putline>>> AUTH LOGIN
<<<getline<<< 504 5.7.4 Unrecognized authentication type
*** Warning ***  The SMTP server does not require AUTH LOGIN.
*** Warning ***  Are you sure server supports AUTH?
>>>putline>>> MAIL FROM:<email@email.com>
<<<getline<<< 530 5.7.1 Client was not authenticated
*** Error ***  The SMTP server does not like the sender name.
*** Error ***  Have you set your mail address correctly?
>>>putline>>> QUIT
<<<getline<<< 221 Closing connection. Good bye.
0
Giovanni HewardCommented:
That particular SMTP server may not require authentication; try modifying the blat command line to omit the following switches:

-u "!username!" -pw "!password!"

Regarding the blat if exist portion: are you running the script from the command line or from Windows directly?  If the latter try the following:

if not exist blat.exe (
      echo Requires http://sourceforge.net/projects/blat/files/
      pause
      goto :eof
)

If you removed cd /d "%~dp0" than the script will look for blat.exe from the current directory.  For example, if you're in c:\test and run c:\test2\script.bat then the script will look in c:\test for blat.exe

Not modifying my final script (using the example above) the script would first change from c:\test to c:\test2 automatically, and search for blat.exe there.

This portion (and the entire script) is tested as working.  If blat.exe isn't in the current folder or the folder where the script resides (depending on whether you removed the cd /d "%~dp0" piece), the missing message will be displayed.

In the end (if you prefer) you can always create a variable for the blat.exe location.  This way you're not concerning yourself with path issues.

Here's an example of that (and no SMTP authentication ) :

@echo off
setlocal enabledelayedexpansion
set blat=c:\bin\blat.exe
if not exist "!blat!" (
      echo Requires http://sourceforge.net/projects/blat/files/
      pause
      goto :eof
)
set recipient="group@domain.com"
set server=127.0.0.1:25
set sender="<user@domain.com>"
set subject=Subject
set body=Body Message.
set loc=c:\temp\*.txt
set log=%~n0.log

echo Searching !loc! please wait...
for /f "delims=" %%f in ('dir !loc! /s/a-d/b') do (
	call :sendfile "%%f"
)
if exist !log! type !log!
goto :eof

:sendfile
if exist %1 (
	echo Sending file: %~1
	"!blat!" -to !recipient! -subject "!subject!" -body "!body!" -server !server! -f !sender! -debug -attach "%~1">>!log! 2>&1
)

Open in new window


Note: If you're automating this script then you'll want to omit pause statements.  Additionally, blat will run with only blat.exe and blat.dll -- the other files were created when blat was compiled and are not required for use.
0
100questionsAuthor Commented:
Please be advised that I do not have the time to test this completely and further at this time, therefore I will presume that this might work, however the reader should be aware that if they want to be sure if this solution works, they should test it out first to ensure if it solves their issue.  Additionally, I cannot ask any other questions and the only way to close this is to select a solution.  Again, please test it yourself to see if in fact it works for you.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Legacy OS

From novice to tech pro — start learning today.