Cannot find an overload for "Add" and the argument count: "1"

10,587

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)
}
Share:
10,587
Leoxanigm
Author by

Leoxanigm

Updated on June 04, 2022

Comments

  • Leoxanigm
    Leoxanigm almost 2 years

    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 = "[email protected]"
    $emailSmtpPass = "xxxxxxxx"
    
    $emailMessage = New-Object System.Net.Mail.MailMessage
    $emailMessage.From = "Xxxx Xxxx <[email protected]>"
    $emailMessage.To.Add( "[email protected]" )
    $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?