def is_authenticated(self, user, password):
host = ""
if self.configuration.has_option("auth", "imap_host"):
host = self.configuration.get("auth", "imap_host")
secure = True
if self.configuration.has_option("auth", "imap_secure"):
secure = self.configuration.getboolean("auth", "imap_secure")
try:
if ":" in host:
address, port = host.rsplit(":", maxsplit=1)
else:
address, port = host, 143
address, port = address.strip("[] "), int(port)
except ValueError as e:
raise RuntimeError(
"Failed to parse address %r: %s" % (host, e)) from e
if sys.version_info < (3, 4) and secure:
raise RuntimeError("Secure IMAP is not availabe in Python < 3.4")
try:
connection = imaplib.IMAP4(host=address, port=port)
try:
if sys.version_info < (3, 4):
connection.starttls()
else:
connection.starttls(ssl.create_default_context())
except (imaplib.IMAP4.error, ssl.CertificateError) as e:
if secure:
raise
self.logger.debug("Failed to establish secure connection: %s",
e, exc_info=True)
try:
connection.login(user, password)
except imaplib.IMAP4.error as e:
self.logger.debug(
"IMAP authentication failed: %s", e, exc_info=True)
return False
connection.logout()
return True
except (OSError, imaplib.IMAP4.error) as e:
raise RuntimeError("Failed to communicate with IMAP server %r: "
"%s" % (host, e)) from e
评论列表
文章目录