如何使用python发送加密和dkim签名的邮件?

如何使用python发送加密和dkim签名的邮件?,python,encryption,smtp,dkim,Python,Encryption,Smtp,Dkim,有了一些web应用程序,我需要使用python发送电子邮件。 我想发送内容加密和使用DKIM签名的邮件。 我‌ 不知道如何在python中或使用哪个库来实现这一点 顺便说一句,我有自己的smtp服务器,使用postfix试试这个: import smtplib, dkim, time, os from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText print('Content-T

有了一些web应用程序,我需要使用python发送电子邮件。 我想发送内容加密和使用DKIM签名的邮件。 我‌ 不知道如何在python中或使用哪个库来实现这一点

顺便说一句,我有自己的smtp服务器,使用postfix

试试这个:

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'] = '"Ur Name" <name@urdomain.com>'
msg['To'] = 'test@gmail.com'
msg['Subject'] = ' Test Subject'

# 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 DKIM/TLS 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( 'your_key.pem')).read()

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

# Generate message signature
sig = dkim.sign(msg.as_string(), b'key1', b'urdomain.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()
导入smtplib、dkim、时间、操作系统
从email.mime.multipart导入MIMEMultipart
从email.mime.text导入MIMEText
打印('内容类型:文本/普通')
打印(“”)
msg=MIMEMultipart('alternative')
msg['From']='urname'
msg['To']='test@gmail.com'
msg['Subject']='testsubject'
#创建消息正文(纯文本和HTML版本)。
text=”“”\
测试电子邮件仅显示为文本
"""
html=”“”\
测试DKIM/TLS电子邮件
测试DKIM的HTML主体
"""
#记录这两部分的MIME类型-text/plain和text/html。
part1=MIMEText(文本“纯”)
part2=MIMEText(html,'html')
附加信息(第1部分)
附加信息(第2部分)
#DKIM私钥,例如:com RSA-2048bit
privateKey=open(os.path.join('your_key.pem')).read()
#以“字节”形式指定标题
headers=[b'from',b'to',b'subject']
#生成消息签名
sig=dkim.sign(msg.as_string(),b'key1',b'urdomain.com',privateKey.encode(),include_headers=headers)
sig=sig.decode()
#添加DKIM签名
msg['DKIM-Signature']=sig[len(“DKIM签名:):]
#通过本地SMTP服务器发送邮件。
s=smtplib.SMTP('localhost')
#sendmail函数接受3个参数:发件人地址、收件人地址
#和要发送的消息-在这里它作为一个字符串发送。
s、 sendmail(msg['From'],msg['To'],msg.as_string())
s、 退出

您可以阅读更多信息。

此邮件通过本地主机smtp发送。我想从smtp服务器发送。@AMZ此代码仅显示加密和签名。您可以使用smtplib选项进行更改。