Alexandros Tzimas
Alexandros Tzimas

Reputation: 43

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('[email protected]', r'thisismypassword')
    smtp_handler = logging.handlers.SMTPHandler(mailhost=('smtp.gmail.com', 587),
                                                fromaddr='[email protected]',
                                                toaddrs=['[email protected]'],
                                                subject='A dashing subject',
                                                credentials=('[email protected]',
                                                             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)

Upvotes: 0

Views: 2256

Answers (2)

Nicolas Penot
Nicolas Penot

Reputation: 40

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.

Upvotes: 1

KJTHoward
KJTHoward

Reputation: 876

When I use Gmail for sending emails from Python I use:

server = smtplib.SMTP_SSL('smtp.gmail.com', 465) 

Also, try connecting to the server just in a regular python shell

server = smtplib.SMTP_SSL('smtp.gmail.com', 465) 
server.login(username, password)

to see if your details are correct, it maybe you need to set up an app password to use Gmail from an application, depending on your security settings

Upvotes: 0

Related Questions