Validate an email address

Exchange PowershellValidating an e-mail address could be really usefull. Here is a really good thing to do before sending that address to a creation/modification script :

Function ValidMail ([string]$Mail ) {
$regexp=”^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}” +
“.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+” +
“.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$”

if ($Mail -match $regexp) {
$return=$True
}
Else {
$return=$False
}
Return $return
}

$regexp contains a regular expression that can validate any mail address, with many sub-domains, and can also contains an IP address in case of…

 

Sending mail using Powershell

Sending an email in powershell can be done, once more, using .Net Frameword 🙂

Function SendMail([string]$file,[string]$sender,[string]$recipients,[string]$server){

$message = new-object System.Net.Mail.MailMessage

$message.from = $sender

$message.subject = “My first mail in Powershell”

$message.body = “Hello,” + “`r`n” +”This mail was sent automatically by the script” + “`r`n” +”You will find in attachement all information  you asked.” + “`r`n” +”Regards”
foreach ($rec in $recipients){$message.TO.add($rec)}

$attachment = new-object System.Net.Mail.Attachment $file
$message.Attachments.Add($attachment)
$client = new-object System.Net.Mail.SmtpClient $server
$client.Send($message)
$attachment.Dispose()
}

Four parameters aremandatory to get all the power of that function : $fichier, $sender, $recipients, $server.

$file : Contains the exact path of the file to include as attachment. (“C:includesfile.doc”)

$sender : Simply the email address of the sender (“sender@mydomain.com”)

$recipients : Contains a list of recipient with that format :

recipient1@domain.com

recipient2@domain2.com

$server : It is the full name of the server that is allowed to send mails.