Powershell Mail module, which sends all the emails in outbox (A. CSV file represents an email ),

Source: Internet
Author: User
Tags argumentlist create zip mail code mailmessage

Powershell Mail module, which sends all the emails in outbox (A. CSV file represents an email ),

Write the creating mail code to the calling place and write the mailxxx.csv file to the outbox. The main content of the email is recorded in the interface.

Write

#template$TMP = IMPORT-CSV "$($dh)\mail\TEMPLATES\MAIL.CSV" #customization$TMP.CC ="" #  $TMP.Subject ="From Server $($( get-wmiobject Win32_ComputerSystem ).Name) By APOMS_TSQL_Deployment_Package $(get-date)." #  test1          $TMP.Body ="$msg`nPlease Check The attachement for details. `nThanks`nBest Regards." #  test##clear if(Test-Path "$logfile.zip" ){Remove-Item -Path "$logfile.zip" -Force|&$log}#create zip"zipping log.."export-Zip -sourcefiles "$logfile" -zipfilename "$logfile.zip"|&$log#add attachements$TMP.Attachments ="$logfile.zip,$($dh)\Mail\msg.txt" #   #wirte-outbox,output mailxxx.csv ConvertTo-Mail -path "$($dh)\mail\outbox\MAIL$t.CSV" -mail $tmp
Send, call the send-avmail.ps1 to send mail

."$($dh)\Mail\Send-AvEmail.ps1" 

Sample

cls;$dh = $pwd.path#$PSScriptRoot =Split-Path -Parent $MyInvocation.MyCommand.Definition$pv = $psversiontable.psversion.major$strDate = Get-Date -Format "yyyyMMdd"$logfile = "$($dh)\log\log$($strDate).txt"$log = {$input|Tee-Object -FilePath $logfile -Append}$filename = ''$rem = {$i = '';1..75|%{$i += '-'};$i } #getting order"start deploying `nat $(get-date)"|&$log"reading configuration file..."|&$log$content = ( Get-Content "$($dh)\module\config_order"| Out-String )$hash = ( Invoke-Expression $content )#$hash #sql parameters$content = ( Get-Content "$($dh)\module\config_sys"| Out-String )$hashsys = ( Invoke-Expression $content )&$rem|&$logtry{ #Display"order`t type"|&$log&$rem|&$log1..20|%{if($hash["$_"] -ne $null){ "$($_)`t $($hash["$_"])"|&$log}}&$rem|&$log"echo The Depoly will start immediately" |&$logsleep 1|&$log&$rem|&$log#hit by order1..20|%{if($hash["$_"] -ne $null){if($dh -ne $pwd.path){cd $dh}$key = $hash["$_"] "........................$key............." |&$log$cmd = "$($dh)\module\RunSqlcmdByKey.ps1 "$dh|&$logInvoke-Expression -Command $cmd |&$log}} }catch {"$(Get-Date) error:$_.Exception"|&$log}finally{"finish deploying at $(get-date)"|&$log$title = "Send mail"$message = "Do you want to Send the logfile to isoftstone?" $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `"Send the logfile to isoftstone." $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `"Continue." $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no) $result = $host.ui.PromptForChoice($title, $message, $options, 1) switch ($result){0 {#import mail moudle"creating attachement"Import-Module "$($dh)\mail\MailModule.psm1" -force $t = Get-Date -Format 'yyyyMMdd_hh_mm_ss' ."$($dh)\Mail\msg.ps1""creating mail"$msg ="FYI."#template$TMP = IMPORT-CSV "$($dh)\mail\TEMPLATES\MAIL.CSV" #customization$TMP.CC ="" #  $TMP.Subject ="From Server $($( get-wmiobject Win32_ComputerSystem ).Name) By APOMS_TSQL_Deployment_Package $(get-date)." #  test1          $TMP.Body ="$msg`nPlease Check The attachement for details. `nThanks`nBest Regards." #  test##clear if(Test-Path "$logfile.zip" ){Remove-Item -Path "$logfile.zip" -Force|&$log}#create zip"zipping log.."export-Zip -sourcefiles "$logfile" -zipfilename "$logfile.zip"|&$log#add attachements$TMP.Attachments ="$logfile.zip,$($dh)\Mail\msg.txt" #   #wirte-outbox,output mailxxx.csv ConvertTo-Mail -path "$($dh)\mail\outbox\MAIL$t.CSV" -mail $tmp#start sending"praparing to send"sleep 10"sending email..."."$($dh)\Mail\Send-AvEmail.ps1" |&$log}1 {}}}
Send-avmail.ps1

#cls;#paths$dh = $pwd.path$pv = $psversiontable.psversion.major$strDate = Get-Date -Format "yyyyMMdd"#log$log_file = "$($dh)\mail\log\log$($strDate).txt"$log = {$input|Tee-Object -FilePath $log_file -Append}$filename = ''$rem = {$i = '';1..75|%{$i += '-'};$i} ################################START#######################################remember$curentFile = ''$pop = $pwd$path = "$($dh)\Mail"CD $path#bodytry {if(Test-Path -Path $path ){ Import-Module "$path\MailModule.psm1" -force $t = Get-Date -Format 'yyyyMMdd_hh_mm_ss' $smtp = Get-Smtp -Path $path Get-Date|&$log#MAX 10foreach($f in $(ls -Path "$path\outbox\*.csv"|sort-object -Property LastWriteTime -Descending|Select-Object -First 10)){&$rem|&$log$curentFile = "$($f.fullname)" $curentFile|&$log#ONE CSV FILE PRESENT ON MAIL MESSAGE.$email = ConvertFrom-MailCsv -Path $curentFile"$($email.subject) is sending.."  #SEND IT$smtp.send($email) "$($email.subject) is sent" #MOVE IT TO FOLDER SENT WHEN SUCCESSMove-Item -Path $curentFile -Destination "$path\sent\$($f.name)"#Tabke a breaksleep 1} }}catch { #log error message$_|&$log"error occur when sending mail:$curentFile"|&$log#MOVE IT TO FOLDER error WHEN failMove-Item -Path $curentFile -Destination "$path\error\$($f.name)"}finally {#mark with dateGet-Date|&$log#popcd $pop}

Mailmodule. psm1

function import-Zip{ param([string]$zipfilename, [string] $destination)if(test-path($zipfilename)){$shellApplication = new-object -com shell.application$zipPackage = $shellApplication.NameSpace($zipfilename)$destinationFolder = $shellApplication.NameSpace($destination)$destinationFolder.CopyHere($zipPackage.Items())}}function export-Zip{ param([string]$sourcefiles, [string]$zipfilename)dir $sourcefiles | foreach-object {if(!$zipfilename) {$zipfile = $_.FullName + ".zip";}else {$zipfile = $zipfilename;}if(!(test-path($zipfile))) {set-content $zipfile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18));(dir $zipfile).IsReadOnly = $false;}$shellApplication = new-object -com shell.application;$zipPackage = $shellApplication.NameSpace($zipfile);$zipPackage.CopyHere(($_.FullName));}}function ConvertFrom-MailCsv{ [CmdletBinding()]param( [System.String]$Path) $Path = "$Path"if(Test-Path -Path $Path){$tmp = Import-Csv -Path $Path$mail = New-Object System.Net.Mail.MailMessage#set the from addresses$MailAddress = $tmp.From$mail.From = New-Object System.Net.Mail.MailAddress($MailAddress) #set the destination addresses$MailtoAddress =$tmp.To$mail.To.Add($MailtoAddress)#set the CC addresses foreach($cca in $tmp.CC -split ','){if($cca -ne "" -and $cca -ne $null){$copy =New-Object System.Net.Mail.MailAddress("$cca");$mail.CC.Add($copy); }}#set the content$mail.Subject = $tmp.Subject$mail.Priority = $tmp.Priority$mail.Body = $tmp.Body#set the attachmentsforeach($filename in $tmp.attachments -split ','){if(Test-Path -Path $filename){$attachment = new-Object System.Net.Mail.Attachment($filename)$mail.Attachments.Add($attachment)}}#add to arrayreturn $mail;}}function ConvertFrom-Mail{ [CmdletBinding()]param( [System.String]$Path) begin {$pop = $pwd cd $Path}process {[System.Net.Mail.MailMessage[]]$mails = @()foreach($f in $(ls -Path $Path -Name "*.csv")){$tmp = Import-Csv -Path $f $mail = New-Object System.Net.Mail.MailMessage#set the from addresses$MailAddress = $tmp.From$mail.From = New-Object System.Net.Mail.MailAddress($MailAddress) #set the destination addresses$MailtoAddress =$tmp.To$mail.To.Add($MailtoAddress)#set the CC addresses foreach($cca in $tmp.CC -split ','){if($cca -ne "" -and $cca -ne $null){$copy =New-Object System.Net.Mail.MailAddress("$cca");$mail.CC.Add($copy); }}#set the content$mail.Subject = $tmp.Subject$mail.Priority = $tmp.Priority$mail.Body = $tmp.Body#set the attachmentsforeach($filename in $tmp.attachments -split ','){if(Test-Path -Path $filename){$attachment = new-Object System.Net.Mail.Attachment($filename)$mail.Attachments.Add($attachment)}}#add to array$mails += $mail;}return $mails;}end {cd $pop}}function Get-Smtp{ param( [System.String]$Path)begin {$pop = $pwdcd $Path}process {$param = Import-Csv ".\smtp.csv"$smtpServer = $param.Server$smtpUser = $param.User$smtpPassword = $($param.Password|ConvertTo-SecureString)$smtp = New-Object System.Net.Mail.SmtpClient -argumentList $smtpServer#$smtp.Credentials = New-Object System.Net.NetworkCredential -argumentList $smtpUser,"Isoft1410"#$smtpPassword$smtp.Credentials = New-Object System.Net.NetworkCredential -argumentList $smtpUser, $smtpPassword return $smtp;}end {cd $pop}}function ConvertTo-Mail{ [CmdletBinding()]param($mail,[System.String]$Path)$mail|Export-Csv -Path $Path}Export-ModuleMember -Function ConvertFrom-Mail, ConvertTo-Mail,Get-Smtp, ConvertFrom-MailCsv,import-Zip,export-Zip

Download:

Http://download.csdn.net/detail/wangzhpwang/8268477
Http://download.csdn.net/detail/wangzhpwang/8268511

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.