python - 在python中使用SMTP_SSL发送邮件

标签 python ssl smtplib pem

我使用以下代码发送带有证书的邮件。我有一个来自邮件服务器的 ca-chain.cert.pem 文件。如何使用这个文件来签名邮件(我必须使用这个pem文件)?

m_server = {
        'username': "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a6a5a487aabeb4a2b5b1a2b5e9aea8" rel="noreferrer noopener nofollow">[email protected]</a>",
        'password': "123435",
        'server': "mail.myserver.io",
        'port': 465,
    }
    message = MIMEMultipart("alternative")
    message["Subject"] = "Notification"
    message["From"] = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a5b58597a5743495f484c5f48145355" rel="noreferrer noopener nofollow">[email protected]</a>"
    message["To"] = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9efffcfddef9f3fff7f2b0fdf1f3" rel="noreferrer noopener nofollow">[email protected]</a>"

    email_body = "<p>test</p>"
    message.attach(MIMEText(email_body, "html"))
    
    with smtplib.SMTP_SSL(m_server['server'], m_server['port']) as server:
        server.set_debuglevel(1)
        server.login(m_server['username'], m_server['password'])
        server.sendmail(m_server['username'], message["To"], message.as_string())

ca-chain.cert.pem文件:该文件与邮件服务器相关

-----BEGIN CERTIFICATE-----
MIIFhTCCA22....
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIFnDCCA4Sg....
-----END CERTIFICATE-----

最佳答案

How to use this file for signing mail(I have to use this pem file)?

邮件未在 SMTP 中签名。基于证书的邮件签名由发件人使用 PGP 或 S/MIME 完成。然后邮件服务器使用 DKIM 完成基于 key 的签名。但各种签名方式都需要私钥,这里不给出。

我的猜测是,给定的证书应该用于在 TLS 握手期间对 SMTP 服务器进行身份验证。要指定证书,需要一个自定义 SSL 上下文,如下所示:

import ssl
ctx = ssl.create_default_context(cafile = 'the-certificates-given-to-you.pem')
with smtplib.SMTP_SSL(m_server['server'], m_server['port'], context=ctx) as server:
    ...

关于python - 在python中使用SMTP_SSL发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66927516/

相关文章:

python - 具有调试和 iPython 集成的 Python IDE?

c# - 如何将 smtp 发送功能添加到我的应用程序

python - Gmail 和 Outlook 将空格注入(inject)超链接 URL

python - 如何以正确的顺序将句子中的单词插入到列表中

python - 在 Python 中发送带有片段标识符的 GET 请求

python运行时错误,可以转储文件吗?

ssl - 自动更新 website.com 和 *.website.com 证书的方式

security - 在线支付需要哪些安全措施?

linux - Certbot 无法找到 _acme-challenge.subdomain.domain.com 的 Route53 托管区域

Python smtplib仅发送消息正文