文件添加到文件夹时的电子邮件通知

时间:2016-02-10 22:17:30

标签: windows batch-file

我对脚本编程知之甚少,但我认为我想要的是可能的。我只想在将文件添加到特定文件夹时收到电子邮件通知。我没有任何特定的软件,所以我想它必须是批处理文件或VBS?

3 个答案:

答案 0 :(得分:3)

您可以在启用了PowerShell的批处理文件中执行此操作:

@echo off
setlocal EnableDelayedExpansion
set "emailUserName=dummyEmail@gmail.com"
set "emailPassword=dummyPassword"
set "target=yourEmail@email.com"
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

为此,您需要创建一个发送电子邮件的虚拟gmail帐户。这支持正文中的HTML标记,如示例所示。

请注意,这不适用于删除文件,仅删除更改和新文件。

答案 1 :(得分:2)

您是否有关于电子邮件服务器的信息?你有什么版本的Windows和Powershell?

这个简短的Powershell脚本适用于我的环境:

$folder = "D:\"
$mailserver = "your.mailserver.your.company"
$recipient = "your.email@your.company"

$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 "alerts@your.company" `
                    -Subject “File Creation Event” `
                    -Body "A file was created: $($eventArgs.FullPath)" `
                    -SmtpServer $mailserver `
                    -Credential $anon
}

使用以下方法停止提醒:

Unregister-Event -SourceIdentifier Created -Force

答案 2 :(得分:0)

我根据@ xXhRQ8sD2L7Z贡献的内容构建了我的解决方案。但是我在测试时收到了多封电子邮件,每次运行注册脚本时都会收到一封新电子邮件。取消注册行无效:

    Unregister-Event -SourceIdentifier Created -Force

所以我发现了这个:Unregister a registered filewatcher event does not work

    Get-EventSubscriber -SourceIdentifier "filechanged" | Unregister-Event

但它仍然无法运行,所以我自己运行Get-EventSubscriber并获得了事件订阅列表,并发现在我的情况下,-SourceIdentifier是一个GUID 。有了这个理解,我抓住了每个GUID并继续取消注册它们。 (我可以通过它们进行循环,但我可能只会使用一次。另外,在我意识到发生了什么之前,我只创建了6次订阅)

这消除了我每次测试时收到的所有额外电子邮件。

    Get-EventSubscriber -SourceIdentifier "<very long GUID>" | Unregister-Event

然后我想发送给多个收件人,所以我发现了这个:Powershell send-mailmessage - email to multiple recipients

    $recipients = "<User1@domain.com>", "<User2@domain.com>"

您还可以使用电子邮件分发组。