Skip to main content
 首页 » 编程设计

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

2024年09月07日45itcoder

有一些网络应用程序,我需要使用 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() 

您可以阅读更多here .