# XintecMailDetected.ps1 by Jason Tai 20170406 # MSW SAVE Mail if detected NDA keyword # chechk all receiver in the RCP file # if any one receiver not list in NDAMailList,send notce mail to all receiver. # else move msg and rcp to check folder # notice 內容 #您好, #由於您傳送的郵件主旨為"%subject%"已違反外寄郵件RIP規定,因您的Mail裡含有非NDA名單內的收件者,依RIP規定無法對外傳送,您有責任通知Xintec所有收件者此為"無效郵件"。 #$NoticeBody = "您好," + "`r`n" #$NoticeBody = $NoticeBody + "由於您傳送的郵件主旨為%subject%已違反外寄郵件RIP規定,因您的Mail裡含有非NDA名單內的收件者,依RIP規定無法對外傳送,您有責任通知Xintec所有收件者此為無效郵件" $NoticeSubject = "違反PIP規定" $NoticeBody = "您好," + "`r`n" + "由於您於"+ "%DATE%" + "傳送的郵件" + "收件者為:" + "`r`n" + "%RCPTS%" +"主旨為" + '"' + "%subject%" + '"' + "`r`n" + "已違反外寄郵件RIP規定,因您的Mail裡含有非NDA名單內的收件者,依RIP規定無法對外傳送,您有責任通知Xintec所有收件者此為無效郵件" #Test reuslt # only sender in list = pass # sender in list and receiver in list = pass # sender in list and receiver not in list = pass # sender and all receiver in list = pass # sender in list and one receiver not in list = pass # 通知信含原有英文主旨 # 通知信含原有中文主旨 cls $APName = "XintecMailDetected" $APVersion = "20170408" $LogPath = "d:\powershell\log\" $MSWSourcePath = "d:\clearswift\MIMEsweeper for SMTP\Mail\SaveAction\NDAKeyword\" $MSWDestPath = "d:\clearswift\MIMEsweeper for SMTP\Mail\Queues\Checked\" $logkeepday = 7 $NDAExportFile = "D:\Powershell\InportEmail\NDAMaillist.txt" $MailKeepPath = "d:\clearswift\MIMEsweeper for SMTP\Mail\SaveAction\NDAKeyword\KeepMail\" $MailKeepDay = 190 $NoticeSender = "EmailAudit@xintec.com.tw" $MailFrom = "customer-support@sbtc.com.tw" $MailServer ="10.10.2.18" $MailRcpts = "jason@sbtc.com.tw","corrina_chiang@xintec.com.tw" $NoticeSBTCFlag = 1 $global:var #SBTC Test $LogPath = "c:\powershell\log\" $NDAExportFile = "c:\powershell\xintecnda.txt" $MSWSourcePath = "C:\xinteclabsource\" $MSWDestPath = "C:\xinteclabdest\" $MailKeepPath = "C:\xinteclabsource\KeepMail\" $NoticeSender = "jason@sbtc.com.tw" $MailServer ="172.16.1.253" #Region SystemCheck # 檢查目錄設定值最後是否有 "\", 如果沒有則加上 if ( -not $LogPath.EndsWith("\") ) {$LogPath = $LogPath + "\"} if ( -not $MailKeepPath.EndsWith("\") ) {$MailKeepPath = $MailKeepPath + "\"} # 檢查相關目錄及旗標檔是否存在 if ( -not (Test-Path $LogPath) ) {New-Item -Path $LogPath -ItemType directory} $FlagPath = $LogPath + "tmp\" if ( -not (Test-Path $FlagPath) ) {New-Item -Path $FlagPath -ItemType directory} $JobDayStampFile = $APName + "JobDayStamp.tmp" if ( -not (Test-Path $MailKeepPath) ) {New-Item -Path $MailKeepPath -ItemType directory} $JobDayStampFile = $FlagPath + $JobDayStampFile if ( -not (Test-Path $JobDayStampFile) ) { get-date (Get-date).AddDays(-1) -UFormat "%Y/%m/%d" > $JobDayStampFile } #endregion #Region 系統變數 $Powershellversion = Get-Host $Powershellversion = $Powershellversion.Version.Major $LogFireName = $LogPath + $APName + (get-date -UFormat "%Y%m%d.log") $JobLog = "" $Results = Get-ItemProperty "HKLM:SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" $HostName = $Results.Hostname $TCPDomainName = $Results.Domain $FQDN = $Results.Hostname + "." + $Results.Domain #EndRegion #region Function function Writelog { $tempvalue = (Get-date -UFormat "%Y/%m/%d %H時 %M分 %S秒" ) + " " + "$args" ;$tempvalue >> $LogFireName ; $global:joblog = $global:joblog + $tempvalue + "`r`n" } function SendAlertToSbtc ( $TempSubject , $SBody ) { $SBTCSMTP = "10.10.2.18","10.10.2.17" $EventTime = (Get-date -UFormat "%Y年%m月%d日%H時%M分%S秒") $Subject = $EventTime + " *** " + $FQDN + " *** " + $TempSubject $TempServer = @() foreach ($t0 in $SBTCSMTP) { $TempServer = $TempServer + $t0 } $SBTCSMTP = $TempServer for ($t0= 0; $t0 -le $SBTCSMTP.count -1 ; $t0 ++) { $global:SendMailFlag = 1 $Sender = "$HostName" + "@" + "$TCPDomainName" $smtp = New-Object System.Net.Mail.SmtpClient $smtp.Host = $SBTCSMTP[$t0] $smtp.send("$Sender","alert@sbtc.com.tw","$Subject","$SBody") trap{ $global:SendMailFlag = 0 ; continue } if ( $global:SendMailFlag -eq 0 ) { WriteLog "Wrong: Send Alert Mail to $SBTCSMTP[$t0] is fail" } else { WriteLog "Send Alert Mail to alert@sbtc.com.tw is success" $t0 = $SBTCSMTP.count + 1 } } } function SendMail ($TempSubject , $Body , $AlertFlagName , $AlertIntervalMin) { $sendalert = 0 $alertflag = $FlagPath + $AlertFlagName if ($alertflagname -and $AlertIntervalMin ) { if (Test-Path $alertflag) { $LastAlert = Import-Clixml $alertflag $Now = Get-Date if ($Now -ge $LastAlert.addminutes($AlertIntervalMin)) { $Now | Export-Clixml $alertflag $sendalert = 1 } else { writelog "低於Alert 間隔時間,所以不發送" } } else { Get-Date | Export-Clixml $Alertflag $sendalert = 1 } } else { $sendalert = 1 } if ($sendalert -eq 1 ) { $EventTime = (Get-date -UFormat "%Y年%m月%d日%H時%M分%S秒") if ( $AddHostnameInAlert -eq 1 ) { $Subject = $EventTime + " *** " + $hname + " *** " +$TempSubject $Body = $EventTime + " *** " + $hname + " *** " + "`r`n" + $body } else { $Subject = $TempSubject } $TempMailRcpts = $MailRcpts foreach ($TempServer in $MailServer) { $AlertRcptSucess = @() foreach ($TempRcp in $TempMailRcpts) { $global:SendMailFlag = 1 $smtp = New-Object System.Net.Mail.SmtpClient $smtp.Host = "$TempServer" $smtp.send("$MailFrom","$TempRcp","$Subject","$Body") trap{ $global:SendMailFlag = 0 ; continue } if ( $global:SendMailFlag -eq 1 ) { $AlertRcptSucess = $AlertRcptSucess + $TempRcp #$TempMailRcpts = $TempMailRcpts -ne $TempRcp writelog "send alert mail to $TempRcp success" } } $TempMailRcpts = $TempMailRcpts -ne $AlertRcptSucess } if ( $TempMailRcpts.length -ge 6 ) {writelog "send alert fail list: $TempMailRcpts"} if ($NoticeSBTCFlag -eq 1) { SendAlertToSbtc $TempSubject $SBody } } } function SendNotice ($TSubject , $TBody, $Trcpt) { foreach ($TempServer in $MailServer) { $AlertRcptSucess = @() $global:SendMailFlag = 1 $smtp = New-Object System.Net.Mail.SmtpClient $smtp.Host = "$TempServer" $smtp.send($NoticeSender ,"$Trcpt","$TSubject","$TBody") trap{ $global:SendMailFlag = 0 ; continue } if ( $global:SendMailFlag -eq 1 ) { $AlertRcptSucess = $AlertRcptSucess + $TempRcp #$TempMailRcpts = $TempMailRcpts -ne $TempRcp writelog "send notice mail to $Trcpt success" } $TempMailRcpts = $TempMailRcpts -ne $AlertRcptSucess } if ( $TempMailRcpts.length -ge 6 ) {writelog "send notice fail list: $TempMailRcpts"} } function ToArray ($SourceObj) { if ($SourceObj) { $fta0 = @() foreach ($ft0 in $SourceObj) { $fta0 = $fta0 + $ft0 } } else { return "Error" } return, $fta0 } function CheckPath ($TargetPath) { if (-not (Test-Path $TargetPath)) { New-Item -Path $TargetPath -ItemType directory } } function ExecSQLCommand () { param ( [string] $SqlQuery ) #SQLAuth = "uid={};pwd={}" ## Windows authentication if ($SQLauth) { $authentication = $SQLAuth } else { $authentication = "Integrated Security=SSPI" } $connectionString = "Provider=sqloledb; " + "Server=$DBHost; " + "Database=$Database; " + "$authentication; " $connection = New-Object System.Data.OleDb.OleDbConnection $connectionString $command = New-Object System.Data.OleDb.OleDbCommand $SqlQuery,$connection $connection.Open() # Fetch the results, and close the connection $adapter = New-Object System.Data.OleDb.OleDbDataAdapter $command $dataset = New-Object System.Data.DataSet $adapter.Fill($dataSet) $connection.Close() #$dataSet.Tables | Select-Object -Expand Rows $Global:Maillist = $dataSet.Tables } #endregion Writelog "----------Job Begin----------" #region 每日第一次執行Script 將會執行的動作 $JobDayStamp = Get-Content $JobDayStampFile if ((Get-date -UFormat "%Y/%m/%d") -ne $JobDayStamp) { #刪除超過保留天數記錄檔 Writelog "刪除超過保留天數記錄檔" $t0 = $APName $t0 = $t0 + "*.log" Get-ChildItem -path $LogPath -Filter $t0 | where {$_.LastWriteTime -lt (Get-Date).AddDays(-$logkeepday) } | Remove-Item writelog "清除超過保存期限郵件" Get-ChildItem -path $MailKeepPath -Recurse | where {$_.LastWriteTime -lt (Get-Date).AddDays(-($logkeepday +1) ) } | Remove-Item -Force writelog "清除空目錄" $t0 = Get-ChildItem -path $MailKeepPath -Directory | where {$_.LastWriteTime -lt (Get-Date).AddDays(-($logkeepday +1) ) } foreach ($t1 in $t0) { $t2 = Get-ChildItem $t1.FullName if ($t2.count -eq 0 ) { Remove-Item $t1.fullname } } Get-date -UFormat "%Y/%m/%d" > $JobDayStampFile } #endregion $MailKeepPath = $MailKeepPath + (Get-date -UFormat "%Y%m%d") + "\" if ( -not (Test-Path $MailKeepPath) ) {New-Item -Path $MailKeepPath -ItemType directory} writelog "Get the number of pending messages" $tmpRCPList = Get-ChildItem $MSWSourcePath -Filter *.rcp #$MSGList = Get-ChildItem - $MSWSourcePath -Filter *.msg" $RcpList = @() ForEach ($t0 in $tmpRCPList ) { $RcpList = $RcpList + $t0 } if ( $RcpList.count -gt 0) { writelog "Number of pending messages:" $RcpList.count $NDAMailList = Get-Content $NDAExportFile foreach ($t1 in $RcpList) { $Getsender = "" $GetRCPTS = @() $GetSubject = "" $GetDate = "" $RCPContent = Get-Content $t1.PSPath for ($t2 = 0; $t2 -le $RCPContent.count -1 ; $t2++) { if ($rcpcontent[$t2].startswith("Recipient:")) { $t3 = $rcpcontent[$t2] $GetRCPTS = $GetRCPTS + $t3.SubString($t3.IndexOf(":")+2) } elseif ($rcpcontent[$t2].startswith("Subject: ")) { $t3 = $rcpcontent[$t2] $GetSubject= $t3.SubString($t3.IndexOf(":")+2) } elseif ($rcpcontent[$t2].startswith("Return-Path:")) { $t3 = $rcpcontent[$t2] $Getsender= $t3.SubString($t3.IndexOf(":")+2) } elseif ( $rcpcontent[$t2].startswith("Arrival-Date:")) { $t3 = $rcpcontent[$t2].Split("(") $t3 = $t3[1] $GetDate = $t3.Split(")") } } #如果寄件者不列於清單內,將郵件搬到keepPath,並發通知信 #繼續檢查收件者是否有不在清單內的,如果有,將郵件搬到keepPath,並發通知信 #將郵件搬到MSWDestPath if ($NDAMailList -contains $Getsender) { $NotinList = @() writelog "Sender in list" #檢測收件者 foreach ($t4 in $GetRCPTS) { if ($NDAMailList -notcontains $t4) { $NotinList = $NotinList + $t4 } } if ($NotinList.count -gt 0) { writelog "get receiver not in list" writelog "not in lis: " $NotinList $RCPTSText = "" foreach ($t0 in $GetRCPTS) { $RCPTSText = $RCPTSText + $t0 + "`r`n" } #發送通知信給寄件者 $NoticeBody = $NoticeBody -replace ("%subject%","$GetSubject") $NoticeBody = $NoticeBody -replace ("%RCPTS%","$RCPTSText") $NoticeBody = $NoticeBody -replace ("%DATE%","$Getdate") sendnotice $NoticeSubject $NoticeBody $Getsender #將郵件搬到keeppath $MsgFile = $t1 -replace (".rcp",".msg") $SourceMsgFile = $MSWSourcePath + $MsgFile $DestMSGFile = $MailKeepPath + $MsgFile Move-Item $SourceMsgFile -Destination $DestMSGFile $SourceRcp = $MSWSourcePath + $t1 $DestRcp = $MailKeepPath + $t1 Move-Item $SourceRcp $DestRcp } else { # write-host "all in list" #將郵件搬到MSWDestPath $MsgFile = $t1 -replace (".rcp",".msg") $SourceMsgFile = $MSWSourcePath + $MsgFile $DestMSGFile = $MSWDestPath + $MsgFile Move-Item $SourceMsgFile -Destination $DestMSGFile $SourceRcp = $MSWSourcePath + $t1 $DestRcp = $MSWDestPath + $t1 $DestRco = $DestRcp -replace ("rcp","rco") Move-Item $SourceRcp $DestRco Rename-Item $DestRco $DestRcp } } else { Writelog "sender not in list" $RCPTSText = "" foreach ($t0 in $GetRCPTS) { $RCPTSText = $RCPTSText + $t0 + "`r`n" } #發送通知信給寄件者 $NoticeBody = $NoticeBody -replace ("%subject%","$GetSubject") $NoticeBody = $NoticeBody -replace ("%RCPTS%","$RCPTSText") $NoticeBody = $NoticeBody -replace ("%DATE%","$Getdate") $NoticeBody = $NoticeBody -replace ("因您的Mail裡含有非NDA名單內的收件者","因您並非NDA名單內") sendnotice $NoticeSubject $NoticeBody $Getsender #將郵件搬到keeppath $MsgFile = $t1 -replace (".rcp",".msg") $SourceMsgFile = $MSWSourcePath + $MsgFile $DestMSGFile = $MailKeepPath + $MsgFile Move-Item $SourceMsgFile -Destination $DestMSGFile $SourceRcp = $MSWSourcePath + $t1 $DestRcp = $MailKeepPath + $t1 Move-Item $SourceRcp $DestRcp } } } else { writelog "No mail waiting for processing" } Writelog "----------Job End----------"