Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email Notification when file added to folder

I know very little about scripting, but I think what I want is possible. I would simply like to get an email notification when a file is added to a particular folder. I don't have any specific software, so I guess it would have to be a batch file or maybe VBS?

like image 942
dingram10 Avatar asked Feb 10 '16 22:02

dingram10


2 Answers

You can do this, in a batch-file with powershell enabled:

@echo off
setlocal EnableDelayedExpansion
set "[email protected]"
set "emailPassword=dummyPassword"
set "[email protected]"
set "subject=File Changed"
FOR %%G IN (*) DO attrib -A "%%G"
:loop
set "body="
FOR %%G IN (*) DO (
    attrib "%%G" | findstr /B /L A 1>nul
    if !errorlevel! equ 0 (
        echo "%%G"
        set "body=!body!^<br ^/^>%%G"
        attrib -A "%%G"
        )
    ) 2>nul
if not "%body%"=="" echo sending email
if not "%body%"=="" set "body=The following files have been changed:!body!"
if not "%body%"=="" powershell.exe -command "Send-MailMessage -From '!emailUserName!' -to '!target!' -Subject '!subject!' -Body '!body!' -BodyAsHtml -SmtpServer 'smtp.gmail.com' -port '587' -UseSsl -Credential (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ('!emailUserName!', (ConvertTo-SecureString -String '!emailPassword!' -AsPlainText -Force)))"
goto :loop

For this to work, you need to create a dummy gmail acount that will send the email. This supports HTML tags in the body, as shown in the example.

Note that this doesn't work on deletion of files, only changes and new files.

like image 148
Dennis van Gils Avatar answered Sep 23 '22 12:09

Dennis van Gils


Do you have information about your email server? What version of Windows and Powershell do you have?

This short Powershell script works in my environment:

$folder = "D:\"
$mailserver = "your.mailserver.your.company"
$recipient = "[email protected]"

$fsw = New-Object System.IO.FileSystemWatcher $folder -Property @{
   IncludeSubdirectories = $true
   NotifyFilter = [IO.NotifyFilters]'FileName'
}

$created = Register-ObjectEvent $fsw -EventName Created -Action {
   $item = Get-Item $eventArgs.FullPath
   $s = New-Object System.Security.SecureString
   $anon = New-Object System.Management.Automation.PSCredential ("NT AUTHORITY\ANONYMOUS LOGON", $s)
   Send-MailMessage -To $recipient `
                    -From "[email protected]" `
                    -Subject “File Creation Event” `
                    -Body "A file was created: $($eventArgs.FullPath)" `
                    -SmtpServer $mailserver `
                    -Credential $anon
}

Stop the alerts with this:

Unregister-Event -SourceIdentifier Created -Force
like image 21
xXhRQ8sD2L7Z Avatar answered Sep 24 '22 12:09

xXhRQ8sD2L7Z