Gatan | AMETEKSkip to Main Content
No options found

Use PowerShell to send email

DigitalMicrograph Script

This script uses Microsoft PowerShell to send out an email. Modify the mail server variables before testing.

Preview

// This script uses Microsoft PowerShell to send out an email'
// Modify the mail server variables below before testing.

string BuildPowerShellScript_SendEmail( string From, string To, string Sub, string Body )
{
	// Mailserver configuration variables. 
	string SMPTPServer	= "smtp.DOMAIN.com"
	number SMPTport		= 587
	number SMPTuseSSL	= 1
	string SMPTLogin		= ""
	string SMPTpassword 	= ""
	
	// Asking for login credentials 
	if ( SMPTLogin == "" || SMPTpassword == "" )
	{
		if ( !GetString( "Enter mail server login", SMPTLogin, SMPTLogin ) ) return ""
		if ( !GetString( "Enter mail server password for '" + SMPTLogin + "'", SMPTpassword , SMPTpassword  ) ) return ""
	}

	// The script below builds a PowerShell script
	String PSscript
	PSscript += "$EmailFrom = '" + from + "';\n"
	PSscript += "$EmailTo = '" + To + "';\n"
	PSscript += "$Subject = '" + Sub + "';\n"
	PSscript += "$Body = '" + Body + "';\n"
	PSscript += "$SMTPServer = '" + SMPTPServer + "';\n"
	PSscript += "$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, " + SMPTport + ");\n"
	PSscript += "$SMTPClient.EnableSsl = " + ( SMPTuseSSL ? "$true" : "$false" ) + ";\n"
	PSscript += "$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( '" 
	PSscript += SMPTLogin + "', '" + SMPTpassword + "' );\n"
	PSscript += "$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body);\n"
	
	return PSscript
}
	
	
void SendEmail( string From, string To, string Sub, string Body )
{
	// The script send to PowerShell
	string PSscript = BuildPowerShellScript_SendEmail( From, To, Sub, Body )	
	if ( PSscript == "" ) return
	
	// Build call-string for PowerShell
	String callString
    callString += "powershell"	// The executable called 
    //	callString += " -NoExit"	// Add this if you want to keep the Powershell console open
    callString += " -Command &{ "
    callString += PSscript			
    callString += " }"
    
    OKDialog( "The following script is send to PowerShell:\n\n" + PSscript )
    LaunchExternalProcess( callString, 10 )	// Call with 10sec timeout
}

SendEmail( "sender@DOMAIN.com", "recepient@DOMAIN.com", "Test-email subject line", "Hi. This is just a test." )