Python smtplib.SMTPRecipientsRefused() Examples

The following are 30 code examples of smtplib.SMTPRecipientsRefused(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module smtplib , or try the search function .
Example #1
Source File: sampleshipment.py    From baobab.lims with GNU General Public License v3.0 7 votes vote down vote up
def send_mail(self, sender, receiver, subject="", body=""):
        """Send email from sender to receiver
        """
        mime_msg = MIMEMultipart('related')
        mime_msg['Subject'] = subject
        mime_msg['From'] = sender
        mime_msg['To'] = receiver
        msg_txt = MIMEText(body, 'plain')
        mime_msg.attach(msg_txt)
        try:
            host = getToolByName(self, 'MailHost')
            host.send(mime_msg.as_string(), immediate=True)
        except SMTPServerDisconnected as msg:
            logger.warn("SMTPServerDisconnected: %s." % msg)
        except SMTPRecipientsRefused as msg:
            raise WorkflowException(str(msg))

    # -------------------------------------------------------------------------- 
Example #2
Source File: gmail.py    From sndlatr with Apache License 2.0 7 votes vote down vote up
def send_rfc822(self, rfc822_mail):
        """
        Send rfc822 mail as fetched via imap. To and from addresses are
        extracted from the rfc822 envolope.
        Returns the rfc message id of the sent message.
        """
        rewriter = MailSendRewriter(rfc822_mail)
        receivers = rewriter.get_receivers()
        rewriter.rewrite()
        if not receivers:
            raise InvalidEmail('no to address')
            # TODO: check for any rejected recepient. Fail if any fails?
        try:
            self.client.sendmail(rewriter.get_from(), receivers,
                                 rewriter.message_as_str())
        except smtplib.SMTPRecipientsRefused:
            raise InvalidEmail('server rejected recepients') 
Example #3
Source File: email_notifications.py    From cstar_perf with Apache License 2.0 6 votes vote down vote up
def send(self):
        s = smtplib.SMTP(self.config['server'], self.config['port'])
        s.ehlo()
        if self.config['ssl']:
            s.starttls()
            s.ehlo()
        if self.config['authenticate']:
            s.login(self.config['user'], self.config['pass'])
        msg = MIMEText(self.body)
        msg['Subject'] = self.subject
        msg['From'] = self.config['from']
        msg['To'] = ", ".join(self.recipients)
        msg['BCC'] = self.config.get('always_bcc', None)
        try:
            s.sendmail(self.config['from'], self.recipients, msg.as_string())
        except smtplib.SMTPRecipientsRefused:
            log.warn("Bad recipients for mail (not an email address?) : {recipients}".format(recipients=self.recipients))
            return False
        log.info("Sent email to {recipients}".format(recipients=self.recipients)) 
Example #4
Source File: utils.py    From hepdata with GNU General Public License v2.0 6 votes vote down vote up
def send_email(destination, subject, message, reply_to_address=None):
    try:
        connection = connect()
        mmp_msg = MIMEMultipart('alternative')
        mmp_msg['Subject'] = subject
        mmp_msg['From'] = reply_to_address if reply_to_address else current_app.config['MAIL_DEFAULT_SENDER']
        mmp_msg['To'] = destination

        part1 = MIMEText(message, 'html', 'utf-8')
        mmp_msg.attach(part1)

        recipients = destination.split(',')
        recipients.append(current_app.config['ADMIN_EMAIL'])

        connection.send_message(mmp_msg, current_app.config['MAIL_DEFAULT_SENDER'], recipients)
        connection.quit()
    except SMTPRecipientsRefused as smtp_error:
        send_error_mail(smtp_error)
    except Exception as e:
        print('Exception occurred.')
        raise e 
Example #5
Source File: tests.py    From jorvik with GNU General Public License v3.0 6 votes vote down vote up
def test_fallimento_recipient(self, mock_smtp):
        """
        In caso di fallimento del recipient  il messaggio viene rimesso in coda se entrambi
        i recipient sono stati rifiutati, altrimenti viene considerato inviato
        """
        codici = (550, 551, 552, 553, 450, 451, 452, 500, 501, 503, 521, 421)
        for codice in codici:
            msg = 'code {}'.format(codice)
            instance = mock_smtp.return_value
            for x in range(2):
                recipients = {
                    self.persone[0].persona.email: (codice, msg) if x in (1, 2) else (250, 'ok'),
                    self.persone[0].email: (codice, msg) if x in (0, 2) else (250, 'ok'),
                }
                instance.sendmail.side_effect = smtplib.SMTPRecipientsRefused(recipients=recipients)
                self._invia_msg_singolo()
                if codice == 501 or x in (0, 1):
                    self.assertEqual(Messaggio.in_coda().count(), 0)
                else:
                    self.assertEqual(Messaggio.in_coda().count(), 1)
                self._reset_coda() 
Example #6
Source File: shipment.py    From baobab.lims with GNU General Public License v3.0 6 votes vote down vote up
def send_mail(self, sender, receiver, subject="", body=""):
        """Send email from sender to receiver
        """
        mime_msg = MIMEMultipart('related')
        mime_msg['Subject'] = subject
        mime_msg['From'] = sender
        mime_msg['To'] = receiver
        msg_txt = MIMEText(body, 'plain')
        mime_msg.attach(msg_txt)
        try:
            host = getToolByName(self, 'MailHost')
            host.send(mime_msg.as_string(), immediate=True)
        except SMTPServerDisconnected as msg:
            logger.warn("SMTPServerDisconnected: %s." % msg)
        except SMTPRecipientsRefused as msg:
            raise WorkflowException(str(msg)) 
Example #7
Source File: smtpd.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused as e:
            print('got SMTPRecipientsRefused', file=DEBUGSTREAM)
            refused = e.recipients
        except (OSError, smtplib.SMTPException) as e:
            print('got', e.__class__, file=DEBUGSTREAM)
            # All recipients were refused.  If the exception had an associated
            # error code, use it.  Otherwise,fake it with a non-triggering
            # exception code.
            errcode = getattr(e, 'smtp_code', -1)
            errmsg = getattr(e, 'smtp_error', 'ignore')
            for r in rcpttos:
                refused[r] = (errcode, errmsg)
        return refused 
Example #8
Source File: smtpd.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused as e:
            print('got SMTPRecipientsRefused', file=DEBUGSTREAM)
            refused = e.recipients
        except (OSError, smtplib.SMTPException) as e:
            print('got', e.__class__, file=DEBUGSTREAM)
            # All recipients were refused.  If the exception had an associated
            # error code, use it.  Otherwise,fake it with a non-triggering
            # exception code.
            errcode = getattr(e, 'smtp_code', -1)
            errmsg = getattr(e, 'smtp_error', 'ignore')
            for r in rcpttos:
                refused[r] = (errcode, errmsg)
        return refused 
Example #9
Source File: smtpd.py    From Imogen with MIT License 6 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused as e:
            print('got SMTPRecipientsRefused', file=DEBUGSTREAM)
            refused = e.recipients
        except (OSError, smtplib.SMTPException) as e:
            print('got', e.__class__, file=DEBUGSTREAM)
            # All recipients were refused.  If the exception had an associated
            # error code, use it.  Otherwise,fake it with a non-triggering
            # exception code.
            errcode = getattr(e, 'smtp_code', -1)
            errmsg = getattr(e, 'smtp_error', 'ignore')
            for r in rcpttos:
                refused[r] = (errcode, errmsg)
        return refused 
Example #10
Source File: send.py    From byro with Apache License 2.0 6 votes vote down vote up
def test(self, from_addr):
        try:
            self.open()
            self.connection.ehlo_or_helo_if_needed()
            self.connection.rcpt("test@example.org")
            (code, resp) = self.connection.mail(from_addr, [])
            if code != 250:
                logger.warning(
                    "Error testing mail settings, code %d, resp: %s" % (code, resp)
                )
                raise SMTPSenderRefused(code, resp, from_addr)
            senderrs = {}
            (code, resp) = self.connection.rcpt("test@example.com")
            if (code != 250) and (code != 251):
                logger.warning(
                    "Error testing mail settings, code %d, resp: %s" % (code, resp)
                )
                raise SMTPRecipientsRefused(senderrs)
        finally:
            self.close() 
Example #11
Source File: smtpd.py    From android_universal with MIT License 6 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused as e:
            print('got SMTPRecipientsRefused', file=DEBUGSTREAM)
            refused = e.recipients
        except (OSError, smtplib.SMTPException) as e:
            print('got', e.__class__, file=DEBUGSTREAM)
            # All recipients were refused.  If the exception had an associated
            # error code, use it.  Otherwise,fake it with a non-triggering
            # exception code.
            errcode = getattr(e, 'smtp_code', -1)
            errmsg = getattr(e, 'smtp_error', 'ignore')
            for r in rcpttos:
                refused[r] = (errcode, errmsg)
        return refused 
Example #12
Source File: models.py    From Bitpoll with GNU General Public License v3.0 6 votes vote down vote up
def send(self, request):
        if (not self.last_email) or self.last_email + timedelta(hours=12) < now():  # TODO: TIMEDELTA mit config
            old_lang = translation.get_language()
            translation.activate(self.user.language)
            link = reverse('poll_vote', args=(self.poll.url,))  # TODO: hier direkt das poll oder das Vote?
            email_content = render_to_string('invitations/mail_invite.txt', {
                'receiver': self.user.username,
                'creator': self.creator.username,
                'link': link
            })
            try:
                send_mail("Invitation to vote on {}".format(self.poll.title), email_content, None, [self.user.email])
                self.last_email = now()
                self.save()
            except SMTPRecipientsRefused:
                translation.activate(old_lang)
                messages.error(
                    request, _("The mail server had an error sending the notification to {}".format(self.user.username))
                )
            translation.activate(old_lang)
        else:
            messages.error(
                request, _("You have send an Email for {} in the last 12 Hours".format(self.user.username))
            ) 
Example #13
Source File: app.py    From Python-Programming-Blueprints with MIT License 6 votes vote down vote up
def _send_message(message):

    smtp = smtplib.SMTP_SSL('email-smtp.eu-west-1.amazonaws.com', 465)

    try:
        smtp.login(
            user='AKIAITZ6BSMD7DMZYTYQ',
            password='Ajf0ucUGJiN44N6IeciTY4ApN1os6JCeQqyglRSI2x4V')
    except SMTPAuthenticationError:
        return Response('Authentication failed',
                        status=HTTPStatus.UNAUTHORIZED)

    try:
        smtp.sendmail(message['From'], message['To'], message.as_string())
    except SMTPRecipientsRefused as e:
        return Response(f'Recipient refused {e}',
                        status=HTTPStatus.INTERNAL_SERVER_ERROR)
    finally:
        smtp.quit()

    return Response('Email sent', status=HTTPStatus.OK) 
Example #14
Source File: smtpd.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused as e:
            print('got SMTPRecipientsRefused', file=DEBUGSTREAM)
            refused = e.recipients
        except (OSError, smtplib.SMTPException) as e:
            print('got', e.__class__, file=DEBUGSTREAM)
            # All recipients were refused.  If the exception had an associated
            # error code, use it.  Otherwise,fake it with a non-triggering
            # exception code.
            errcode = getattr(e, 'smtp_code', -1)
            errmsg = getattr(e, 'smtp_error', 'ignore')
            for r in rcpttos:
                refused[r] = (errcode, errmsg)
        return refused 
Example #15
Source File: views.py    From Bitpoll with GNU General Public License v3.0 6 votes vote down vote up
def _send_mail_or_error_page(subject, content, address, request):
    try:
        send_mail(subject, content, None, [address])
    except SMTPRecipientsRefused as e:
        wrong_email, (error_code, error_msg) = e.recipients.items()[0]
        unknown = 'User unknown' in error_msg
        if not unknown:
            error_email_content = u'{0}: {1}'.format(e.__class__.__name__,
                                                     repr(e.recipients))
            send_mail(
                _('Registration: Sending mail failed: {}'.format(address)),
                error_email_content,
                None,
                [settings.TEAM_EMAIL])
        return TemplateResponse(request, 'registration/email_error.html', {
            'unknown': unknown,
            'error_code': error_code,
            'error_msg': error_msg,
            'recipient': wrong_email
        })

    return redirect('registration_request_successful', address) 
Example #16
Source File: tasks.py    From helfertool with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_news_mails(first_language, append_english, subject, text, text_en, unsubsribe_url):
    prev_language = translation.get_language()

    count = 0
    for person in Person.objects.all():
        # build mail text
        mail_text = ""
        tmp_unsubscribe_url = unsubsribe_url + str(person.token)

        if append_english:
            mail_text += render_to_string("news/mail/english.txt")

        mail_text += _mail_text_language(first_language, text, tmp_unsubscribe_url)

        if append_english:
            mail_text += _mail_text_language("en", text_en, tmp_unsubscribe_url)

        mail_text = mail_text.lstrip().rstrip()

        tracking_header = new_tracking_news(person)

        # send mail
        try:
            mail = EmailMessage(subject,
                                mail_text,
                                settings.EMAIL_SENDER_ADDRESS,
                                [person.email, ],
                                headers=tracking_header)
            mail.send(fail_silently=False)
        except smtplib.SMTPRecipientsRefused:
            pass

        count += 1

        # wait a bit after a batch of mails
        if count >= settings.MAIL_BATCH_SIZE:
            count = 0
            time.sleep(settings.MAIL_BATCH_GAP)

    translation.activate(prev_language) 
Example #17
Source File: hooksets.py    From open-humans with MIT License 5 votes vote down vote up
def send_confirmation_email(self, *args, **kwargs):
        try:
            super(OpenHumansHookSet, self).send_confirmation_email(*args, **kwargs)
        except SMTPRecipientsRefused:
            logger.warn("Unable to send confirmation mail.") 
Example #18
Source File: smtpd.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients 
Example #19
Source File: smtpd.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients 
Example #20
Source File: tv_grab_IO.py    From tvgrabpyAPI with GNU General Public License v3.0 5 votes vote down vote up
def send_mail(self, message, mail_address, subject=None):
        try:
            if isinstance(message, (list,tuple)):
                msg = u''.join(message)

            elif isinstance(message, (str,unicode)):
                msg = unicode(message)

            else:
                return

            if subject == None:
                subject = 'Tv_grab_nl3_py %s' % self.config.in_output_tz('now').strftime('%Y-%m-%d %H:%M')

            msg = MIMEText(msg, _charset='utf-8')
            msg['Subject'] = subject
            msg['From'] = mail_address
            msg['To'] = mail_address
            try:
                mail = smtplib.SMTP(self.config.opt_dict['mailserver'], self.config.opt_dict['mailport'])

            except:
                sys.stderr.write(('Error mailing message: %s\n' % sys.exc_info()[1]).encode(self.local_encoding, 'replace'))
                return

            mail.sendmail(mail_address, mail_address, msg.as_string())

        except smtplib.SMTPRecipientsRefused:
            sys.stderr.write(('The mailserver at %s refused the message\n' % self.config.opt_dict['mailserver']).encode(self.local_encoding, 'replace'))

        except:
            sys.stderr.write('Error mailing message\n'.encode(self.local_encoding, 'replace'))
            sys.stderr.write(traceback.format_exc())

        mail.quit()
    # send_mail()

# end Logging 
Example #21
Source File: test_smtplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_421_from_rcpt_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
        with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
            smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
        self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')}) 
Example #22
Source File: smtpd.py    From RevitBatchProcessor with GNU General Public License v3.0 5 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients 
Example #23
Source File: smtpd.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients 
Example #24
Source File: smtpd.py    From unity-python with MIT License 5 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients 
Example #25
Source File: test_smtplib.py    From android_universal with MIT License 5 votes vote down vote up
def test_421_from_rcpt_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
        with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
            smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
        self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')}) 
Example #26
Source File: smtpd.py    From canape with GNU General Public License v3.0 5 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients 
Example #27
Source File: test_sending.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def recipients_refused(patch_token_manager, monkeypatch, request):
    monkeypatch.setattr('inbox.sendmail.smtp.postel.SMTPConnection',
                        erring_smtp_connection(smtplib.SMTPRecipientsRefused,
                                               {'foo@foocorp.com':
                                                (550, request.param)}))


# Different providers use slightly different errors, so parametrize this test
# fixture to imitate them. 
Example #28
Source File: postel.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def _handle_sending_exception(self, err):
        if isinstance(err, smtplib.SMTPServerDisconnected):
            raise SendMailException(
                'The server unexpectedly closed the connection', 503)

        elif isinstance(err, smtplib.SMTPRecipientsRefused):
            raise SendMailException('Sending to all recipients failed', 402)

        elif isinstance(err, smtplib.SMTPResponseException):
            # Distinguish between permanent failures due to message
            # content or recipients, and temporary failures for other reasons.
            # In particular, see https://support.google.com/a/answer/3726730

            message = 'Sending failed'
            http_code = 503

            if err.smtp_code in SMTP_ERRORS:
                for stem in SMTP_ERRORS[err.smtp_code]:
                    if stem in err.smtp_error:
                        res = SMTP_ERRORS[err.smtp_code][stem]
                        http_code = res[0]
                        message = res[1]
                        break

            server_error = '{} : {}'.format(err.smtp_code, err.smtp_error)

            self.log.error('Sending failed', message=message,
                           http_code=http_code, server_error=server_error)

            raise SendMailException(message, http_code=http_code,
                                    server_error=server_error)
        else:
            raise SendMailException('Sending failed', http_code=503,
                                    server_error=str(err)) 
Example #29
Source File: test_sending.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def recipients_refused(patch_token_manager, monkeypatch, request):
    monkeypatch.setattr('inbox.sendmail.smtp.postel.SMTPConnection',
                        erring_smtp_connection(smtplib.SMTPRecipientsRefused,
                                               {'foo@foocorp.com':
                                                (550, request.param)}))


# Different providers use slightly different errors, so parametrize this test
# fixture to imitate them. 
Example #30
Source File: smtpd.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients