Mohammad Changani
Mohammad Changani

Reputation: 476

Send mail with SMTP_SSL in python

I'm using the following code to send a mail with the certificate. I have a ca-chain.cert.pem file from the mail server. How to use this file for signing mail(I have to use this pem file)?

m_server = {
        'username': "[email protected]",
        'password': "123435",
        'server': "mail.myserver.io",
        'port': 465,
    }
    message = MIMEMultipart("alternative")
    message["Subject"] = "Notification"
    message["From"] = "[email protected]"
    message["To"] = "[email protected]"

    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 file: this file is related to the mail server

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

Upvotes: 2

Views: 3265

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123451

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

Mails do not get signed in SMTP. Certificate based signatures for mail are done by the sender with PGP or S/MIME. Then there are key based signatures done by the mail server with DKIM. But all of the various ways to sign need a private key, which is not given here.

My guess is that the given certificates should instead be used to authenticate the SMTP server during the TLS handshake. To specify the certificate one would need a custom SSL context, something like this:

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:
    ...

Upvotes: 2

Related Questions