用python的smtplib发送使用dkim签名的电子邮件 « Xiaoxia[PG]
用python的smtplib发送使用dkim签名的电子邮件
最终效果
如下,能够使我们发送的邮件直接到达对方的收件箱,而不是被当作垃圾邮件。
制作DKIM密钥
使用openssl生成我们所需要的Private Key和Public Key。
X:\sign>openssl genrsa -out rsa.private 1024
WARNING: can't open config file: /home/drangon/work/mingw-w64-dgn/lib_bin/openssl/ssl/openssl.cnf
Loading 'screen' into random state - done
Generating RSA private key, 1024 bit long modulus
..................++++++
................................++++++
e is 65537 (0x10001)
X:\sign>openssl rsa -in rsa.private -out rsa.public -pubout -outform PEM
WARNING: can't open config file: /home/drangon/work/mingw-w64-dgn/lib_bin/openssl/ssl/openssl.cnf
writing RSA key这样得到rsa.private和rsa.public两个文本文件。
域名配置DKIM
在域名控制面板,除了需要给域名(例如xsign.org)设置MX记录,还要添加一项dkim的TXT记录。
假设dkim的Selector是s1(可以有多个Selector,表示可以使用多个dkim证书),则要设置的是:s1._domainkey.xsign.org TXT
内容为:
k=rsa; t=y; p=[Public Key的内容]
可以使用nslookup检查是否已经生效。
I:\Users\Administrator>nslookup
默认服务器: ns3.gd.cnmobile.net
Address: 221.179.38.7> set type=TXT
> s1._domainkey.xsign.org
服务器: ns3.gd.cnmobile.net
Address: 221.179.38.7非权威应答:
s1._domainkey.xsign.org text ="t=y; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC1OmB7qZbFWqAgl51jS
U0Opn/wdJaB2mTkkPgD+gW3ccjXTazgYZVkokCeD+67oceWw42mLTkzg402Vc+IaIk+L57GULVxzECw8
mWtR7jOcG3UOnuaRMScX8uRlnllXj6v1SQTHljW2M++D/hj3dn8lDWxWw0s8IbesSb3far8XQIDAQAB"SMTP发送代码
需要用到python的dkim库和dnspython.org提供的dns库。
- import smtplib, email, dkim
- import dns.resolver
- def sendmail(mailfrom, mailto, msg):
- domain = email.Utils.unquote(mailto).split("@")[1]
- host = dns.resolver.query(domain, "MX")[0].exchange
- smtp = smtplib.SMTP(str(host))
- smtp.sendmail(mailfrom, [mailto], msg)
- smtp.quit()
- if __name__ == "__main__":
- msg = "From: [email protected]\r\n" \
- "To: [email protected]\r\n" \
- "Subject: Hi\r\n\r\n" \
- "I miss you!!!!\r\n"
- sig = dkim.sign(msg, "s1", "xsign.org", open("./rsa_private.txt").read())
- msg = sig + msg
- print msg
- sendmail("[email protected]", "[email protected]", msg)
- print "ok"
运行程序,即发送了一封邮件到[email protected]的收件箱里。
验证DKIM
GMail里可以看到dkim的验证已经通过!
Authentication-Results: mx.google.com; spf=softfail (google.com: domain of transitioning [email protected] does not designate 120.196.50.109 as permitted sender) [email protected]; dkim=pass (test mode) [email protected]
Date: Tue, 24 May 2011 10:51:43 -0700 (PDT)
Message-Id: <[email protected]>
DKIM-Signature: v=1; a=rsa-sha256; c=simple/simple; d=xsign.org;
[email protected]; q=dns/txt; s=s1; t=1306259500; h=From : To : Subject;
bh=5yC7rMxS78DH//OfCDEEHnf4nFVZ21IFPtApH3ARSkg=; b=ASqTJBKbhDzVcj59AYR7kUI7WF+o5GJHje5iN6JqiCtVTk/DQaft58sridQu4YMTFfadmuPRnUfGia/CU2nJFnzeJmGq9nQIRctwsLdUWIKGxc5xp3eZ0H4rU57WAuDJPRQdea7Vaf4sNotDHEldKC1lHsSgdROYbhE12CZjNpI=
From: [email protected]
To: [email protected]
Subject: HiI miss you!!!!