Thursday, August 11, 2016

PowerShell: Gmailing / Emailing Screenshots

I totally scraped the script from AdminAresenal. Kris Powell wrote such a good solution that I lifted it and added a gmailer process. I'm posting this solution in case someone needs to automate emailing of screenshots. The automation component is Task Scheduler.  My scheduled job uses "powershell -executionpolicy unrestricted -windowstyle minimized c:\scripts\screenshots.ps1" so I don't have the PowerShell script window appear in each screenshot.

#Create a timestamp-based BMP filename

$filename = (get-date).tostring().replace('/','.').replace(':','.')

#Create a folder for your outputted screenshots
$File = "c:\scripts\ss\$filename.bmp"

## From the AdminArsenal blog ##
Add-Type -AssemblyName System.Windows.Forms
Add-type -AssemblyName System.Drawing

# Gather Screen resolution information
$Screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
$Width = $Screen.Width
$Height = $Screen.Height
$Left = $Screen.Left
$Top = $Screen.Top

# Create bitmap using the top-left and bottom-right bounds
$bitmap = New-Object System.Drawing.Bitmap $Width, $Height

# Create Graphics object
$graphic = [System.Drawing.Graphics]::FromImage($bitmap)

# Capture screen
$graphic.CopyFromScreen($Left, $Top, 0, 0, $bitmap.Size)

# Save to file
$bitmap.Save($File) 

#Now we send that screenshot via GMail
#Enable "Less Secure Apps" in order to use SMTP via script
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "yourgmailaccount@gmail.com"
$Password = "P@$$w0rd"

$to = "addressee@gmail.com"
$cc = "anotherperson@someotherdomain.com"
$subject = "Screenshot taken $filename"
$body = "Screenshot Attachment"
$attachment = $file

$message = New-Object System.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-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)