Search code examples
pythonsmtpsmtpclientsmtplibssmtp

Checking the emails logs while using Python smtplib


I wrote a simple program that sends email using smtplib. The program works perfectly and sends the email. Is there any option that I can view all the logs during the communication? Meaning is it possible to print or to view the smtp conversation that happened?


Solution

  • First you should check documentation for smtplib - see set_debuglevel

    with smtplib.SMTP_SSL(f'{host}:{port}') as server:
    
        server.set_debuglevel(1)
    
        server.login(login, password)
        server.sendmail(sender_email, recipients, message.as_string())
    

    For .set_debuglevel(1) it displays

    send: 'ehlo [127.0.1.1]\r\n'
    reply: b'250-smtp.googlemail.com at your service, [79.163.228.253]\r\n'
    reply: b'250-SIZE 35882577\r\n'
    reply: b'250-8BITMIME\r\n'
    reply: b'250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\r\n'
    reply: b'250-ENHANCEDSTATUSCODES\r\n'
    reply: b'250-PIPELINING\r\n'
    reply: b'250-CHUNKING\r\n'
    reply: b'250 SMTPUTF8\r\n'
    reply: retcode (250); Msg: b'smtp.googlemail.com at your service, [79.163.228.253]\nSIZE 35882577\n8BITMIME\nAUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8'
    send: 'AUTH PLAIN ********\r\n'
    reply: b'235 2.7.0 Accepted\r\n'
    reply: retcode (235); Msg: b'2.7.0 Accepted'
    

    For .set_debuglevel(2) it adds timestamps

    21:26:26.602350 send: 'ehlo [127.0.1.1]\r\n'
    21:26:26.632756 reply: b'250-smtp.googlemail.com at your service, [79.163.228.253]\r\n'
    21:26:26.632871 reply: b'250-SIZE 35882577\r\n'
    21:26:26.632917 reply: b'250-8BITMIME\r\n'
    21:26:26.632957 reply: b'250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\r\n'
    21:26:26.633022 reply: b'250-ENHANCEDSTATUSCODES\r\n'
    21:26:26.633072 reply: b'250-PIPELINING\r\n'
    21:26:26.633112 reply: b'250-CHUNKING\r\n'
    21:26:26.633151 reply: b'250 SMTPUTF8\r\n'
    21:26:26.633201 reply: retcode (250); Msg: b'smtp.googlemail.com at your service, [79.163.228.253]\nSIZE 35882577\n8BITMIME\nAUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8'
    

    It sends it on standard error so if you want to get it in file 'output.txt' then you would have to redirect sys.stderr

    import sys
    
    old_stderr = sys.stderr
    
    sys.stderr = open('output.txt', 'w')
    
    with smtplib.SMTP_SSL(f'{host}:{port}') as server:
    
        server.set_debuglevel(1)
    
        server.login(login, password)
        server.sendmail(sender_email, recipients, message.as_string())
    
    sys.stderr = old_stderr