def send_mails(self, connection, last_sent=None, user_settings=None):
        """
        Does the lookups and sends out email digests to anyone who has them due.
        """

        self.logger.debug("Entering send_mails()")

        try:
            connection.open()
        except:
            self.logger.error("Could not use e-mail connection")
            raise

        if not user_settings:
            user_settings = models.Settings.objects.all().order_by('user')

        context = {'user': None,
                   'username': None,
                   'notifications': None,
                   'digest': None,
                   'site': Site.objects.get_current()}

        for setting in user_settings:
            context['user'] = setting.user
            context['username'] = getattr(setting.user, setting.user.USERNAME_FIELD)
            context['notifications'] = []
            # get the index of the tuple corresponding to the interval and
            # get the string name
            context[
                'digest'] = nyt_settings.INTERVALS[
                [y[0] for y in nyt_settings.INTERVALS].index(setting.
                                                             interval)][
                1]
            for subscription in setting.subscription_set.filter(
                send_emails=True,
                latest__is_emailed=False
            ):
                context['notifications'].append(subscription.latest)
            if len(context['notifications']) > 0:
                # STMP connection send loop
                while True:
                    try:
                        self._send_user_notifications(context, connection)
                        for n in context['notifications']:
                            n.is_emailed = True
                            n.save()
                        break
                    except smtplib.SMTPSenderRefused:
                        self.logger.error(
                            "E-mail refused by SMTP server ({}), skipping!".format(setting.user.email))
                        continue
                    except smtplib.SMTPException as e:
                        self.logger.error(
                            "You have an error with your SMTP server connection, error is: {}".format(e))
                        self.logger.error("Sleeping for 30s then retrying...")
                        time.sleep(30)
                    except Exception as e:
                        self.logger.error(
                            "Unhandled exception while sending, giving up: {}".format(e))
                        break
dataset/ETHPy150Open benjaoming/django-nyt/django_nyt/management/commands/notifymail.py/Command.send_mails/original