How to start TLS on an active connection in python?

后端 未结 1 1524
我寻月下人不归
我寻月下人不归 2021-01-05 02:26

The following is my current code for connecting to gmail\'s smtp server on port 587. After issuing the STARTTLS command how would I finish negotiating the TLS session and be

相关标签:
1条回答
  • 2021-01-05 03:19

    You can ssl wrap a connected socket. This will give you the idea:

    import ssl
    import base64
    from socket import *
    
    
    cc = socket(AF_INET, SOCK_STREAM)
    cc.connect(("smtp.gmail.com", 587))
    # cc.read(..)
    
    cc.send('helo tester.com\r\n')
    cc.send('starttls\r\n')
    # cc.read(..) If the server responds ok to starttls
    #             tls negotiation needs to happen and all
    #             communication is then over the SSL socket 
    
    scc = ssl.wrap_socket(cc, ssl_version=ssl.PROTOCOL_SSLv23)
    scc.send('auth login\r\n')
    # scc.read(..)
    
    scc.send(base64.b64encode('username')+'\r\n')
    scc.send(base64.b64encode('password')+'\r\n')
    
    # css.send(
    #  mail from:
    #  rcpt to:
    #  data
    #  etc
    

    look at the AUTH LOGIN section of this page for info about the username/password encoding: http://www.samlogic.net/articles/smtp-commands-reference-auth.htm

    After that the AUTH LOGIN command has been sent to the server, the server asks for username and password by sending BASE64 encoded text (questions) to the client. “VXNlcm5hbWU6” is the BASE64 encoded text for the word "Username" and “UGFzc3dvcmQ6” is the BASE64 encoded text for the word "Password" in the example above. The client sends username and password also using BASE64 encoding. "adlxdkej", in the example above, is a BASE64 encoded username and "lkujsefxlj" is a BASE64 encoded password.

    0 讨论(0)
提交回复
热议问题