Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save HumanEquivalentUnit/2f3d7cd0bac23eeaf6eff8f1f996aab3 to your computer and use it in GitHub Desktop.
Save HumanEquivalentUnit/2f3d7cd0bac23eeaf6eff8f1f996aab3 to your computer and use it in GitHub Desktop.
PowerShell script to export SSL Certificate delivery emails to .crt files
# Automates Outlook
# - searches the Inbox for Thawte
# 'your SSL certificate has been approved' messages
# - extracts the certificate to disk with a useful filename
# - deletes the emails
$VerbosePreference = 'continue'
$OutputFolder = '\\server\share\SSL Cert Deliveries\'
Write-Verbose -Message "Writing to output folder: '$OutputFolder'"
$sslCertSubjects = @(
'Your Thawte SSL123 Certificate Is Approved'
'Your SSL Web Server Certificate Is Approved'
'Your SSL Web Server Wildcard Certificate Is Approved'
'Your SSL Web Server with EV Is Approved'
)
$outlook = New-Object -ComObject Outlook.Application
$namespace = $outlook.GetNameSpace("MAPI")
$inbox = $namespace.GetDefaultFolder(6) #6 is Inbox
$inbox.Items | Where-Object {
$sslCertSubjects -contains $_.Subject
} | ForEach-Object {
Write-Verbose -Message "Checking {$($_.Subject)} Email sent on $($_.SentOn)"
if ($_.SenderEmailAddress.endsWith('@thawte.com') -and $_.Body -match '(?ms)Order number: (?<OrderNumber>[^\r\n]+).*common name: (?<CN>[^\r\n]+).*(?<Cert>-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE-----)')
{
Write-Verbose -Message "Processing Email sent on $($_.SentOn)"
# read the certificate's "valid from, until" properties
$Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate
$Cert.Import([System.Text.Encoding]::ASCII.GetBytes($Matches['Cert']))
$StartDate = [datetime]::ParseExact($Cert.GetEffectiveDateString(), 'dd/MM/yyyy HH:mm:ss', [cultureinfo]::InvariantCulture)
$EndDate = [datetime]::ParseExact($Cert.GetExpirationDateString(), 'dd/MM/yyyy HH:mm:ss', [cultureinfo]::InvariantCulture)
# Make a filename
$FileBaseName = '{0} - {1} - {2} to {3}.crt' -f $Matches['OrderNumber'], $Matches['CN'].Trim(), $StartDate.Year, $EndDate.Year
# make filename valid for wildcard certs *.example.com
$FileBaseName = $FileBaseName.Replace('*', 'star')
$FileFullName = Join-Path -Path $OutputFolder -ChildPath $FileBaseName
Write-Verbose -Message " Certificate details / filename: $FileBaseName"
if (-not (Test-Path -LiteralPath $FileFullName))
{
$null = New-Item -ItemType File -Path $FileFullName -Value $Matches['Cert']
}
else
{
Write-Verbose -Message " File exists already, not writing"
}
$_.Delete()
}
else
{
Write-Verbose -Message "Email wasn't from Thawte, or body didn't match the SSL cert regex"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment