#This script file is intended to provide an example script used to test email connectivity for the vDiskReplicator Script.

#This script was created by Rob Zylowski Citrix CCS
#It should be used as an example of how to send emails using powershell.
#
#Although every effort has been made to ensure that these sample scripts work properly, 
#Citrix disclaims any responsibility for any and all liability or responsibility for any 
#damages that may result from using these scripts. 
#The sample scripts are provided to you as is, with no warranty or guarantees.
#

function Get-ScriptDirectory{
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value
 Split-Path $Invocation.MyCommand.Path
}

#Main Script ----------------------------------------------------------------------------

$ScriptSource = Get-ScriptDirectory
$CredFile = "$ScriptSource\..\config\credemail.txt"

$EmailConfigFile = "$ScriptSource\..\config\emailconfig.txt"
#Check for email settings if not there skip email
If (Test-Path $EmailConfigFile)
	{
	$EmailConfig = Get-Content $EmailConfigFile 

	$txtMailRelay = $EmailConfig[0]
	$txtMailFrom = $EmailConfig[1]
	$txtMailTo = $EmailConfig[2]
	$chkUseMailAuth = $EmailConfig[3]
	$chkUseMailSSL = $EmailConfig[4]
	$chkUseMailTLS = $EmailConfig[5]
	$txtMailAcct = $EmailConfig[6]
	$txtMailSubject = $EmailConfig[7]
	$txtMailBody = $EmailConfig[8]
	
	If ($chkUseMailAuth -eq "Use Auth")
	{
		If (Test-Path $CredFile)
		{
			$passwordback = Get-Content $CredFile | ConvertTo-SecureString
			$credential = New-Object System.Management.Automation.PsCredential("mailman",$passwordback)
			$MailmanPW = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($credential.Password))
			$MyPassword = $MailmanPW
		}	
		else
		{
			Write-Host "No Credentials defined.  Email cannot be sent."
			Write-Host ""
			exit
		}
		
		If ($chkUseMailSSL -eq "Use SSL")
		{
			$SMTPClient = New-Object Net.Mail.SmtpClient($txtMailRelay, 465)
			$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($txtMailAcct, "$MyPassword")
			$SMTPClient.EnableSsl = $true
		}
		ElseIf ($chkUseMailTLS -eq "Use TLS")
		{
			$SMTPClient = New-Object Net.Mail.SmtpClient($txtMailRelay, 587)
			$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($txtMailAcct, "$MyPassword")
			$SMTPClient.EnableSsl = $true
		}
		else
		{
			$SMTPClient = New-Object Net.Mail.SmtpClient($txtMailRelay, 25)
			$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($txtMailAcct, "$MyPassword")
			$SMTPClient.EnableSsl = $false
		}
	}
	Else
	{
		$SMTPClient = New-Object Net.Mail.SmtpClient($txtMailRelay, 25)
	}

	Write-Host "Sending Test Email To $txtMailTo at mail relay $txtMailRelay ...."

	$message = New-Object Net.Mail.MailMessage($txtMailFrom, $txtMailTo, $txtMailSubject, $txtMailBody)
	$message.IsBodyHtml = $true;
	$SMTPClient.Send($message)	
	$message.Dispose()
}	

