param( [Parameter(Mandatory = $true)][string]$RequestPath, [string]$ConfigPath = (Join-Path (Split-Path -Parent $PSScriptRoot) 'config.ini'), [switch]$Send, [string]$PickupDirectory ) $ErrorActionPreference = 'Stop' . (Join-Path $PSScriptRoot 'campaign-common.ps1') if ([bool]$Send -eq [bool]$PickupDirectory) { throw 'Choose exactly one mode: -Send or -PickupDirectory' } $context = Get-MailContext -ConfigPath $ConfigPath $request = Read-CampaignRequest $RequestPath $settings = $context.Settings if ($settings['SMTP_TLS'] -ne 'on' -or $settings['SMTP_STARTTLS'] -ne 'on') { throw 'SMTP_TLS and SMTP_STARTTLS must both be on' } $port = 0 if (-not [int]::TryParse($settings['SMTP_PORT'], [ref]$port) -or $port -lt 1 -or $port -gt 65535) { throw 'Invalid SMTP_PORT' } $db = Open-MailDatabase $context $client = $null $message = $null $password = $null try { $review = Get-CampaignReview $context $request $db Assert-ReviewToken $request $review $message = New-Object System.Net.Mail.MailMessage $message.From = New-Object System.Net.Mail.MailAddress($review.Identity.From) $null = $message.ReplyToList.Add($review.Identity.ReplyTo) $null = $message.To.Add($review.Identity.TestTo) $message.Subject = '[TEST] ' + $review.Subject $message.SubjectEncoding = [System.Text.Encoding]::UTF8 $view = [System.Net.Mail.AlternateView]::CreateAlternateViewFromString( $review.Html, [System.Text.Encoding]::UTF8, 'text/html') foreach ($image in $review.Images) { $stream = New-Object System.IO.MemoryStream -ArgumentList (,([byte[]]$image.Bytes)) $resource = New-Object System.Net.Mail.LinkedResource($stream, $image.Type) $resource.ContentId = $image.Cid $resource.TransferEncoding = [System.Net.Mime.TransferEncoding]::Base64 $null = $view.LinkedResources.Add($resource) } $null = $message.AlternateViews.Add($view) $client = New-Object System.Net.Mail.SmtpClient($settings['SMTP_HOST'], $port) $client.Timeout = 20000 if ($Send) { $password = Load-SmtpPassword $context $client.UseDefaultCredentials = $false $client.Credentials = New-Object System.Net.NetworkCredential -ArgumentList @($settings['SMTP_USER'], $password) $client.EnableSsl = $true } else { if (-not (Test-Path -LiteralPath $PickupDirectory -PathType Container)) { throw 'Pickup directory does not exist' } $client.DeliveryMethod = [System.Net.Mail.SmtpDeliveryMethod]::SpecifiedPickupDirectory $client.PickupDirectoryLocation = [System.IO.Path]::GetFullPath($PickupDirectory) } $client.Send($message) Write-CampaignAudit $db 'campaign_test_accepted' $review.Token ("Internal test to $($review.Identity.TestTo)") Write-Output "Campaign test accepted for $($review.Identity.TestTo). Check the received message before approval." if ($Send) { $sentNote = Save-SentCopySafely $settings $password $message; if ($sentNote) { Write-Output $sentNote } } } finally { if ($client) { $client.Dispose() } if ($message) { $message.Dispose() } if ($password) { $password.Dispose() } $db.Dispose() }