通过 Python 为自定义 MTA 生成 DKIM 签名

use*_*950 2 python email base64 sha256 dkim

好的,所以我并没有完全迷失 DKIM。我知道使用公钥等进行编码和设置 DNS 记录的一般规则。我遇到的问题是合并出站电子邮件的“动态”签名并注入到我的标头中,因为我的 MTA 是自定义的,用以下语言编写python是从头开始的,不是开箱即用的。想知道是否有人有一个使用 DKIM 发送一封电子邮件的小 Python 示例,并完成所有操作。就像使用您的私钥生成 256 位加密体一样,该私钥与您的 dns 设置中的姊妹(公钥)密钥相匹配。

小智 8

我要感谢 Georg Zimmer 的上述回答。我在 Python 3.6.2 上运行时遇到了一些困难,因为自 2.x 版本以来,一些“字节”/“字符串”项已经发生了变化。下面是制作 MIMEMultipart(文本/HTML)并使用 DKIM 签名的代码。我用的是 dkimpy-0.6.2。

我的第一篇 StackOverflow 帖子。希望它能帮助你...

import smtplib, dkim, time, os

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


print('Content-Type: text/plain')
print('')
msg = MIMEMultipart('alternative')
msg['From'] = 'test@example.com'
msg['To'] = 'person@anotherexample.com'
msg['Subject'] = ' Test Subject'
msg['Message-ID'] = "<" + str(time.time()) + "-1234567890@example.com" + ">"

# Create the body of the message (a plain-text and an HTML version).
text = """\
Test email displayed as text only
"""

html = """\
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
    <head>
        <title>Test DKMI Email</title>
    </head>
    <body>
        HTML Body of Test DKIM
    </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

# DKIM Private Key for example.com RSA-2048bit
privateKey = open(os.path.join('C:\\dev\\python\\', '2048.example.com.priv')).read()

# Specify headers in "byte" form
headers=[b'from', b'to', b'subject', b'message-id']

# Generate message signature
sig = dkim.sign(msg.as_bytes(), b'introduction', b'example.com', privateKey.encode(), include_headers=headers)
sig = sig.decode()

# Add the DKIM-Signature
msg['DKIM-Signature'] = sig[len("DKIM-Signature: "):]

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()
Run Code Online (Sandbox Code Playgroud)