send mail attachment powershell - powershell

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"

Related

Error sending mail which worked previously

Below is the code snippet used to send mail. which worked until recently and is giving “Failure sending mail." Error. (Version: 5.1.16299.98)
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = " "
$Password = " "
$to = " "
$cc = " "
$subject = "AUTOMATED "
$message = New-Object System.Net.Mail.MailMessage
$message.Subject = $subject
$message.To.Add($to)
$message.Cc.Add($cc)
$message.From = $username
$message.IsBodyHtml = $true
$message.Body =
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username,$Password);
$smtp.Send($message)
Write-Host "Mail Sent"
The error is:
Exception calling "Send" with "1" argument(s): "Failure sending mail."
At F:\powershell_scripts\xxx.ps1 :88 char:1
+ $smtp.Send($message)
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
I can't tell you what the problem is, but I can help you to find out more information about your error!
try {
<your code>
}
catch {
Write-Warning $Error[0].Exception.StackTrace
throw
}
$Error is a special variable in PowerShell that contains a list of the errors that have occurred. Check the documentation for more [/proper] explanation.
$Error[0] is the "most recent" error in the stack.
There are plenty of other properties of the $Error object that you may wish to interrogate for more verbose information... start with
$Error | Get-Member
and go from there.
Hope this helps you get to the bottom of this [and future] issue[s]!

Unable to Send Outlook Email via Powershell

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()
}

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

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

Silently handle errors in powershell

I am writing a troubleshooting script to determine which IP addresses in our Domain are accessible by WMI, and which are not. The script will read a list of input parameters (about 18,000 lines), and will output to a file the IP address and the username
IP address, Username
Problem is, when the WMI error is thrown, it writes to the file
IP address, Get-WmiObject : The RPC server is unavailable. .....numerous lines of error
I would like to make it such that when a WMI error it thrown, it writes the following
IP address, "WMI ERROR"
And here is the modified code for reference
#script_modified.ps1
$abc = $args
$startInfo = $NULL
$process = $NULL
$standardOut = $NULL
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$a = Get-Content "C:\Script\test_input.txt"
foreach ($b in $a){
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
$startInfo.Arguments = "C:\script\script2.ps1 " + $b
$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
$startInfo.Username = "service.infosec"
$startInfo.Domain = "Central"
$startInfo.Password = $password
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$standardOut = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
# $standardOut should contain the results of "C:\script\script2.ps1"
Add-Content C:\script\list_of_computers_in_DOMAIN.log $b","$standardOut
}
EDIT
#Hyper Anthony
I updated my code to the following
try{
$process.StartInfo = $startInfo
}
catch{
$message = "WMI ERROR"
}
finally{
$process.WaitForExit()
Add-Content C:\script\list_of_computers_in_DOMAIN.log $b","$message
}
And I get following errors:
Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
At C:\script\script_modified.ps1:36 char:29
+ $process.WaitForExit <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
How to fix?
EDIT:
Below is the updated code:
foreach ($b in $a){
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
...More Code...
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
try{
$process.Start() | Out-Null
$standardOut = $process.StandardOutput.ReadToEnd()
}
catch{
$standardOut = "WMI ERROR"
}
finally{
$process.WaitForExit()
Add-Content C:\script\list_of_computers_in_DOMAIN.log $b","$standardOut
}
}
There are no longer any errors that get output to the console, BUT, the output file is not as I wish.
When there is an WMI error, I would like the following line to be written
'sender-ip=10.10.10.10', WMI Error
But instead, the following is written
'sender-ip=10.10.10.10',Get-WmiObject : The RPC server is unavailable.
(Exception from HRESULT: 0x800706BA) ...many lines of error
or any other error may be printed instead of WMI Error.
Thanks once again!

powershell send email with binary attachment

How do I send an email containing a binary file using powershell script? Below is my failing best attempt
$to = 'andy.boo#boo.com'
$subject = 'boo'
$file = 'inf.doc'
$from = $to
$filenameAndPath = (Resolve-Path .\$file).ToString()
[void][Reflection.Assembly]::LoadWithPartialName('System.Net') | out-null
$message = New-Object System.Net.Mail.MailMessage($from, $to, $subject, $subject)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath, 'text/plain')
$message.Attachments.Add($attachment)
$smtpClient = New-Object System.Net.Mail.SmtpClient
$smtpClient.host = 'smtp.boo.com'
$smtpClient.Send($message)
Exception calling "Send" with "1" argument(s): "Failure sending mail."
At C:\email.ps1:15 char:17
+ $smtpClient.Send <<<< ($message)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
What version of PowerShell? If you're using version 2.0 save yourself the trouble and just use the Send-MailMessage cmdlet.
If version 1.0:
$msg = new-object system.net.mail.MailMessage
$SMTPClient = new-object system.net.mail.smtpClient
$SMTPClient.host = "smtp server"
$msg.From = "Sender"
$msg.To.Add("Recipient")
$msg.Attachments.Add('<fullPathToFile')
$msg.Subject = "subject"
$msg.Body = "MessageBody"
$SMTPClient.Send($Msg)
Found this.. which is a lot better
Send-MailMessage -smtpServer smtp.doe.com -from 'joe#doe.com' -to 'jane#doe.com' -subject 'Testing' -attachment foo.txt