Someone asked me how to create DKIM by PowerShell without DKIM manager.
Here is an example:
function Delete-DkimDomain($domainName)
{
$DkimManager = New-Object -ComObject EADKIMMgrObj.Manager
$removeCertitifcate = $True
$DkimManager.Domains.Remove($domainName, $removeCertitifcate)
}
# this function can export public key by name
function Export-DkimPublicKey($domainName)
{
$DkimManager = New-Object -ComObject EADKIMMgrObj.Manager
$Domain = $DkimManager.Domains.Item($domainName)
if(!$Domain) {
Write-Error -Message "$domainName is existent"
return ""
}
return $Domain.PublicKey
}
function Create-DkimDomain($domainName, $pfx, $password) {
$DkimManager = New-Object -ComObject EADKIMMgrObj.Manager
if($DkimManager.Domains.Item($domainName)) {
Write-Error -Message "$domainName is existent"
return $null
}
# if no certificate is specified, create a certificat automatically.
if(!$pfx)
{
$password = "TMP001"
$pfx = $DkimManager.GetCertFileName($domainName)
$DkimManager.CreatePFX('CN=' + $domainName, $pfx, $password)
}
$DkimDomain = New-Object -ComObject EADKIMMgrObj.Domain
$DkimDomain.Name = $domainName
$DkimDomain.Selector = "s1024"
$DkimDomain.Active = $True
# Dkim and DomainKeys 0, Dkim Only 1, DomainKeys Only 2 (because DomainKeys is deprecated by Dkim, so Dkim Only is recommended)
$DkimDomain.SignatureType = 1
# rsa-sha1 0, rsa-sha256 1, sha256 is only supported on Windows 2008 or later version.
$DkimDomain.RSAType = 1
# canonicalization algorith, nofws_relaxed 0, simple 1
$DkimDomain.Algorithm = 0
# 0: key pair is stored in pfx file, 1: key pair is stored in a certificate in LocalMachine Store.
# if 1 is used, CertificateThumbprint should be specified.
$DkimDomain.KeyLocation = 0
#
# pfx file name and password
$DkimDomain.CertificateFile = $pfx
$DkimDomain.CertificatePassword = $password
# $DkimDomain.CertificateThumbprint = ""
# True: sign part of message (not recommended)
$DkimDomain.SignPart = $False
$DkimDomain.SignLength = 0
# because system message is failure report and MAPI message is internal message, so we don't sign those messages.
$DkimDomain.SignSystemMessage = $False
$DkimDomain.SignMAPIMessage = $False
$DkimManager.Domains.Add($DkimDomain)
return $DkimDomain
}
$pfx = ""
$password = ""
$domainName = "testdomain.net"
Delete-DkimDomain($domainName)
$Domain = Create-DkimDomain $domainName $pfx $password
if($Domain)
{
Write-Host "$domainName is created"
#display domain
$Domain
$publicKey = Export-DkimPublicKey($domainName)
"public key is: v=DKIM1; k=rsa; p={0}" -f $publicKey
#Delete it
Delete-DkimDomain($Domain.Name)
}