Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Send Nil email if no attachment

$
0
0

Hi,

This script send email with attachment successfully, my requirement is if their is no attachment it must send a email as Nil No Attachment.

FunctionWrite-Log($LogText){
$LogEntry=@"
$((Get-Date).ToString("dd-MM-yyyy HH:mm:ss")) > $($LogText)
"@
$LogEntry
$LogEntry | Add-Content'c:\send\Log\success.txt'
}
$rootfolder='C:\send'
$files=Get-ChildItem"$rootfolder\CSV\*.csv"
$def="username@gmail.com"
$from=$def

ForEach($filein$files){
Write-Log"Found file $file"
$content=Get-Content-Path$file
$content=$content-replace'"',''
}
$content | ConvertFrom-Csv-delimiter'|' | ForEach-Object{
#Import-CSV $file | ForEach-Object{
$attachment="$rootfolder\rar\$($_.shippernbr).rar"
$shippernbr= ($_.Shippernbr)
$sub='Subject #'+' '+$shippernbr
$Body='Dear Sir, Please find attachment. Thanks.'

Write-Log"Attachment is $($attachment)"
$email=$_.email
Write-Log"Email address is $($email)"
$emailCC=$_.emaillCC
Write-Log"Email CC address is $($emailcc)"

If($_.Email){
[System.Net.ServicePointManager]::ServerCertificateValidationCallback= { return$true }
$SMTPServer="smtp.gmail.com"
$SMTPPort="587"
$Username=$from
$Password="password"

$to=$email
$cc=$emailcc
$subject=$sub
$body=$Body
$attachment=$attachment

$message=New-ObjectSystem.Net.Mail.MailMessage
$message.subject=$subject
$message.body=$body
$message.to.add($to)
$message.cc.add($cc)
$message.from=$username
$message.attachments.add($attachment)

$smtp=New-ObjectSystem.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL=$true
$smtp.Credentials=New-ObjectSystem.Net.NetworkCredential($Username, $Password);
$smtp.send($message)

if($?){
Write-Log"Email Sent Successfully"
Move-Item$file
-Destination "$rootfolder\Archive\"
Write-Log "Moved file $($file) to $rootfolder\Archive\"
Move-Item $attachment -Destination "$rootfolder\Archive\"
Write-Log "Moved file $($attachment) to $rootfolder\Archive\"
}else{
Write-Log "Email Send failed: $($error[0])";break
}
}
}

 


Viewing all articles
Browse latest Browse all 6937

Trending Articles