PowerShell – Send Mail

Problem

  • You want to send a mail via a script or using the console

Solution

try
{
$smtpServer = “mailserver.yourserver”
$smtpPort = “25”
$smtpUser = “user”
$smtpPwd = “password”

$msg = New-Object System.Net.Mail.MailMessage
$msg.From = “admin@mailserver.yourserver”
$msg.To.Add(“user@othermailserver”)
$msg.Subject = “A Subject”
$msg.Body = “The Message”
$msg.IsBodyHtml = $false

$smtp = New-Object System.Net.Mail.SmtpClient($smtpServer, $smtpPort)
$smtp.Credentials = New-Object System.Net.NetworkCredential($smtpUser, $smtpPwd)

$smtp.Send($msg)
}
catch
{
exit 1
}

PowerShell – Check TCP Port

Problem

  • You want to check if a TCP port is open.
  • You want to use the PowerShell.

Solution

This solution checks, if port 80 on 192.168.2.1 is open.

try{
    $tcp=new-object System.Net.Sockets.TcpClient
    $tcp.Connect("192.168.2.1",80)
    If($tcp.Connected)
    {
        Write-Host "It works"
    }
    else
    {
        Write-Host "It doesnt work"
    }
    $tcp.Close()
}
catch {
  Write-Host "Error"  
}