I got two different scripts and combined them to check a specific folder for new file and email that file as attachment.
Here's the code combined:
Param (
$Path = "C:\path"
)
$File = Get-ChildItem $Path | Where { $_.LastWriteTime -ge [datetime]::Now.AddMinutes(-10) }
If ($File)
{
$emailSmtpServer = "smtp.xxxx.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "xxxx#xxxxxx.com"
$emailSmtpPass = "xxxxxxxx"
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "Xxxx Xxxx <xxxx#xxxxxx.com>"
$emailMessage.To.Add( "xxxx#xxxxxx.com" )
$emailMessage.Subject = "File Test Report"
$emailMessage.IsBodyHtml = $false
$emailMessage.Body = "Weekly Report"
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$attachment = $File
$emailMessage.Attachments.Add($attachment)
$SMTPClient.Send($emailMessage)
}
The code works fine, it looks for new file and sends the email except it won't attach the file and I get the following error
Cannot find an overload for "Add" and the argument count: "1".
At D:\SendEmail2.ps1:24 char:1
+ $emailMessage.Attachments.Add($attachment)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
I think it has something to do with calling the file with $attachment = $File
Can anyone help?
You probably have to create a Attachment object first and also have to deal with multiple files so replace the following lines:
$attachment = $File
$emailMessage.Attachments.Add($attachment)
with:
$File | ForEach-Object {
$filePath = $_.FullName
$attachment = new-object Net.Mail.Attachment($filePath)
$emailMessage.Attachments.Add($attachment)
}
i had the same issue as you and this fixed it.
https://community.spiceworks.com/posts/8438625
just change:
$path = "D:\FTP-COR\$($today.Year)\$($today.ToString("MM-dd-yyyy"))"
and add your credentials.
I am using PowerShell: (I use .NET so don't forget C#, please don't ask):-)
create a .csv file:
$collection | Export-Csv -Path $SaveAs -NoTypeInformation
To create the attachment object:
[System.Net.Mail.Attachment] $Attachment = [System.Net.Mail.Attachment]::new($SaveAs)
Then to attach to the message object:
$message.Attachments.Add($Attachment)
This should work. I have been using this and it's been working fine. I know it's in PowerShell, but at the core, same .NET
Related
I need to email and attached all file from the folder but no include any sub-folder.
I am getting error
Cannot find an overload for "Add" and the argument count: "1".
At line:11 char:1
$emailMessage.Attachments.Add($getallfiles)
below is the powershell code.
$dir = "C:\Users\myid\Documents\comparsion\src\main\resources\excelfiles\Compare_Result_Files"
$getallfiles = Get-ChildItem "$dir\*.xlsx"
$emailSmtpServer = "mailhub-au.com"
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "donotreply#company.com"
$emailMessage.To.Add( "myid#company.com" )
$emailMessage.Subject = "Selenium Report"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = "Test Summary Attached"
$emailMessage.Body = "$getallfiles"
$emailMessage.Attachments.Add($getallfiles)
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer ,$emailSmtpServerPort )
$SMTPClient.Send($emailMessage)`
You need to loop through the files and add one at a time.
Also the Attachments.Add() method requires the full file name, not a FileInfo object. See the docs
foreach ($file in $getallfiles) {
[void]$emailMessage.Attachments.Add($file.FulllName)
}
I would also suggest adding the -File switch to Get-ChildItem to ensure you only gather files, not folders.
I have a folder that contains several PDF files. They have a unique identifier within the filename that is two characters. Example: XYZ_A1_123.pdf, XYZ_QQ_456.pdf, etc. A1 and QQ are the identifiers.
The identifiers match specific email addresses. I have a CSV file that has two columns, the ID and the matching email address. I can't get my script to look for that specific identifier and send the file. If the PDF file has only the identifier in the name, such as "A1.pdf", the script works fine. Here's my code so far. Also, I'm looking to add a progress bar but not sure how. Any help is appreciated. Thanks!
$csv = Import-Csv "," -path C:\Test\emails.csv -header "id","email"
foreach ($item in $csv) {
$filename = "$($item.id).pdf"
}
$emailSmtpServer = "smtp.gmail.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "email#address.com"
$emailSmtpPass = "mypassword"
$emailFrom = "me#address.com"
$emailTo = $item.email
$emailMessage = New-Object System.Net.Mail.MailMessage( $emailFrom , $emailTo )
$emailMessage.Subject = "This is the subject"
#$emailMessage.IsBodyHtml = $true #true or false depends
$emailMessage.Body = "This is the body."
$emailMessage.Attachment = $filename
$emailMessage.Attachments.add($filename)
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer ,
$emailSmtpServerPort )
$SMTPClient.EnableSsl = $True
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(
$emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )
Creating a test file to mimic the file you described with codes and e-mail addresses:
echo "AF,a#p.com" > test.csv
echo "QC,q#p.com" >> test.csv
cat .\test.csv
The following snippet will pull the file's code, compare it to the address list, and retrieve the e-mail address if present:
$addresses = Import-Csv -Path .\test.csv -Header code, address
$files = ls .\*.pdf
foreach ($file in $files) {
$file_code = $file.name.Split('_')[1]
$addresses | where { $_.code -eq $file_code } | select address
# ...send email...
}
Looks like you've got the e-mail stuff on-lock so I won't rehash that here. I'd only do the e-mail stuff if you find a matching address.
I'm working on a project(bonus points) for my intro CyberSec class and I have a cmd script to create a file with info in a usb drive i was trying to use powershell to send the email to myself but keep getting this error:
At D:\mail.ps1:6 char:16
+ $att= $USBDRIVE\file.zip
+ ~~~~~~~~~
Unexpected token '\file.zip' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
here is my powershell script in the entirety.
$USBDRIVE= Get-WMIObject Win32_Volume | ? { $_.label -eq 'ARNOLDHMW' } |
select -expand driveletter
Compress-Archive -Path $USBDRIVE\file -DestinationPath $USBDRIVE\file.zip
$email = "*"
$pass = "*"
$att= $USBDRIVE\file.zip
$smtpServer = "smtp.gmail.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.EnableSSl = $true
$msg.From = "$email"
$msg.To.Add("$email")
$msg.IsBodyHTML = $true
$msg.Subject = "Files Captured"
$msg.Body = "
</br>
Hi there
"
$msg.Attachments.Add($att)
$SMTP.Credentials = New-Object System.Net.NetworkCredential("$email",
"$pass");
$smtp.Send($msg)
email and password blanked out for obvious reasons
i'm at a loss here. thanks for the help in advance!
I'm pretty sure the issue you are having is because the value you pass to assign $att isn't a string value. Try assigning the variable as a string instead
$att = "$USBDrive\File.zip"
or better yet
$att = Join-Path -Path $USBDrive -ChildPath "file.zip"
I can create an email and display it with my script, but for some reason it doesn't send and I receive the following error. Am I missing something, maybe there's a permissions issue?
Exception calling "Send" with "0" argument(s): "Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))"At C:\TEMP\Scripts\PowerShell\Outlook EMail Creation\TestEMailSend.ps1:27 char:5
+ $mail.Send()
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
My code:
$global:UserReportsToEmail = "my.email#domain.com"
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$mail.To = "$global:UserReportsToEmail"
$mail.cc = "EMAIL#domain.com"
$mail.Subject = "mySubject"
$mail.HTMLBody =
"<font color ='blue'><b>TESTING STUFFFF!</b></font><br>
Text on a new line $UserID"
$mail.Send()
$inspector = $mail.GetInspector
$inspector.Display()
According to a few of the Microsoft sites (e.g. https://social.msdn.microsoft.com/Forums/en-US/80c66a08-66ee-4ab6-b629-6b1e70143eb0/operation-aborted-exception-from-hresult-0x80004004-eabort-outlook-appointment?forum=outlookdev ) this is due to 'object model guard'. A security feature to prevent automated programs from doing stuff like auto-emailing out viruses and stuff from the background.
You probably already worked this out. Posting this here so that others like myself can more quickly and easily understand why its not working.
you can use the Send-MailMessage CmdLets : https://technet.microsoft.com/en-us/library/hh849925.aspx
then when i need more controls and dispose functionnality i use System.Net.Mail.SmtpClient
try
{
$emailCredentials = Import-Clixml "C:\testMail\credentials.clixml"
$recipients = #("user#mail.com", "user2#mail.com", "user3#mail.com")
$attachments = #("C:\testMail\file.txt", ""C:\testMail\file2.txt", "C:\testMail\file3.txt")
# create mail and server objects
$message = New-Object -TypeName System.Net.Mail.MailMessage
$smtp = New-Object -TypeName System.Net.Mail.SmtpClient($buildInfoData.BuildReports.Mail.Server)
# build message
$recipients | % { $message.To.Add($_) }
$message.Subject = $subject
$message.From = New-Object System.Net.Mail.MailAddress($emailCredentials.UserName)
$message.Body = $mailHtml
$message.IsBodyHtml = $true
$attachments | % { $message.Attachments.Add($(New-Object System.Net.Mail.Attachment $_)) }
# build SMTP server
$smtp = New-Object -TypeName System.Net.Mail.SmtpClient(smtp.googlemail.com)
$smtp.Port = 572
$smtp.Credentials = [System.Net.ICredentialsByHost]$emailCredentials
$smtp.EnableSsl = $true
# send message
$smtp.Send($message)
Write-Host "Email message sent"
}
catch
{
Write-Warning "$($_.Exception | Select Message, Source, ErrorCode, InnerException, StackTrace | Format-List | Out-String)"
}
finally
{
Write-Verbose "Disposing Smtp Object"
$message.Dispose()
$smtp.Dispose()
}
I have this working on my local machine, but when I try it on another machine, that has the same files in the same place etc, it fails with this error.
function email
{
$emailSmtpServer = "smtp-mail.outlook.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "USERNAME"
$emailSmtpPass = "PASSWORD"
$attachment = "C:\BackupLog.log"
$emailMessage.Attachments.Add($attachment)
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "myemail#hotmail.co.uk"
$emailMessage.To.Add( "myemail#civil.lmco.com" )
$emailMessage.Subject = "Database Issues"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = "Test"
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer ,$emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )
}
This is the output
PS C:\Users\XXLOCKRG1> email
You cannot call a method on a null-valued expression
At C:\database_backups\powershell scripts\functions\email.ps1:8 char:34
+ $emailMessage.Attachments.Add <<<< ($attachment)
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You have two lines of code in the wrong order:
$emailMessage.Attachments.Add($attachment) # $emailMessage isn't instantiated yet
$emailMessage = New-Object System.Net.Mail.MailMessage
Should be:
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.Attachments.Add($attachment)
You need to instantiate your object before you can reference its members.
You're trying to add an attachment to the $emailMessage object before you actually create it.
$emailMessage.Attachments.Add($attachment) #<---This is causing the error
$emailMessage = New-Object System.Net.Mail.MailMessage
Just rearrange the lines, put the New-Object line before the .Attachments.Add() line.
With that being said, have you tried using the Send-MailMessage cmdlet? It shipped with PowerShell 3.0 and is much, much much easier than using the old SMTP object.