Search code examples
pythonemaillogginghandlersmtplib

Python logging.SMTP handler is not working


What I am trying to do is create a separate logger that will send error logs via email. However, every time I call the email_logger.error('...'), the following error occurs:

smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server.

The code I am using is displayed bellow:

logging.basicConfig(level=logging.INFO, format='%(asctime)s :: %(funcName)s :: %(levelname)s :: %(message)s')

email_logger = logging.getLogger(__name__)
email_logger.setLevel(logging.WARNING)

with smtplib.SMTP('smtp.gmail.com', 587) as server:
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login('host_email@gmail.com', r'thisismypassword')
    smtp_handler = logging.handlers.SMTPHandler(mailhost=('smtp.gmail.com', 587),
                                                fromaddr='host_email@gmail.com',
                                                toaddrs=['mymail@gmail.com'],
                                                subject='A dashing subject',
                                                credentials=('host_email@gmail.com',
                                                             r'thisismypassword'),
                                                secure=None)
    formatter = logging.Formatter('%(asctime)s : %(funcName)s : %(levelname)s : %(name)s : %(message)s')
    smtp_handler.setFormatter(formatter)
    email_logger.addHandler(smtp_handler)

Solution

  • I've got the same issue while sending emails through the logging module to an Amazon STMP server (Amazon SES). I solved this by using secure=().

    Because when sending an email to an STMP that imposes the secure mode, the secure option must not be None. This is the code use internally by the logging module to send email:

                if self.username:
                    if self.secure is not None:
                        smtp.ehlo()
                        smtp.starttls(*self.secure)
                        smtp.ehlo()
                    smtp.login(self.username, self.password)
                smtp.send_message(msg)
                smtp.quit()
    

    Thus, to use the secure mode without passing parameters to smtp.starttls, I set the secure option to () and it solved my issue: it properly uses a TLS connection to send email to the SMTP server.