Exemplo n.º 1
0
def test_send_mail_SENDER_REFUSED(caplog):
    with patch('bote.Mailer._Mailer__send_starttls',
               side_effect=smtplib.SMTPSenderRefused(123, 'foo', 'foo')):
        mailer = bote.Mailer(false_but_valid_mail_settings)
        with pytest.raises(smtplib.SMTPSenderRefused):
            mailer.send_mail('random subject', 'random content')
        assert "SMTP server refused sender" in caplog.text
Exemplo n.º 2
0
def test_remote_refused_sender(mock_send, mailer, message, caplog):
    mock_send.side_effect = smtplib.SMTPSenderRefused(
        550, b'5.1.0 Address rejected.', '*****@*****.**')
    mailer.send(message)

    assert len(caplog.record_tuples) == 1
    _, severity, msg = caplog.record_tuples[0]
    assert severity == logging.ERROR
    assert 'Failed to send message: Sender rejected.' in msg
Exemplo n.º 3
0
 def test_admin_add_user_with_invalid_email(self):
     admin = self._create_admin()
     self.client.force_login(admin)
     params = dict(username='******',
                   email='*****@*****.**',
                   password1='tester',
                   password2='tester')
     params.update(self.add_user_inline_params)
     with patch('allauth.account.models.EmailAddress.objects.add_email') as mocked:
         mocked.side_effect = smtplib.SMTPSenderRefused(501, '5.1.7 Bad sender address syntax',
                                                        'test_name@test_domain')
         self.client.post(reverse('admin:openwisp_users_user_add'), params)
         mocked.assert_called_once()
Exemplo n.º 4
0
 def sendmail(self, from_address, to_addresses, message):
     if self.reject_mail_to in from_address:
         raise smtplib.SMTPSenderRefused(
             -1, 'Failed successfuly', from_address)
     rejected_recipients = dict([
         (addr, 'Fail') for addr in to_addresses
         if self.reject_mail_to in addr])
     if rejected_recipients:
         if len(rejected_recipients) == to_addresses:
             raise smtplib.SMTPRecipientsRefused(rejected_recipients)
         else:
             return rejected_recipients
     if self.host == 'reject_malformed':
         raise smtplib.SMTPDataError(-1, 'I pretend that this is bad data')
Exemplo n.º 5
0
    def sendmail(self,
                 from_addr,
                 to_addrs,
                 msg,
                 mail_options=[],
                 rcpt_options=[]):

        yield self.ehlo_or_helo_if_needed()
        esmtp_opts = []
        if isinstance(msg, str):
            msg = smtplib._fix_eols(msg).encode('ascii')
        if self.does_esmtp:

            if self.has_extn('size'):
                esmtp_opts.append("size=%d" % len(msg))
            for option in mail_options:
                esmtp_opts.append(option)

        (code, resp) = yield self.mail(from_addr, esmtp_opts)
        if code != 250:
            if code == 421:
                self.close()
            else:
                yield self._rset()
            raise smtplib.SMTPSenderRefused(code, resp, from_addr)
        senderrs = {}
        if isinstance(to_addrs, str):
            to_addrs = [to_addrs]
        for each in to_addrs:
            (code, resp) = yield self.rcpt(each, rcpt_options)
            if (code != 250) and (code != 251):
                senderrs[each] = (code, resp)
            if code == 421:
                self.close()
                raise smtplib.SMTPRecipientsRefused(senderrs)
        if len(senderrs) == len(to_addrs):
            # the server refused all our recipients
            yield self._rset()
            raise smtplib.SMTPRecipientsRefused(senderrs)
        (code, resp) = yield self.data(msg)
        if code != 250:
            if code == 421:
                self.close()
            else:
                yield self._rset()
            raise smtplib.SMTPDataError(code, resp)
        #if we got here then somebody got our mail
        return senderrs
Exemplo n.º 6
0
 def test_fallimento_sender(self, mock_smtp):
     """
     In caso di fallimento del sender il messaggio viene rimesso in coda,
     tranne che in caso di errore 5XX che è permanente
     """
     codici = (451, 452, 500, 501, 421)
     for codice in codici:
         msg = 'code {}'.format(codice)
         instance = mock_smtp.return_value
         instance.sendmail.side_effect = smtplib.SMTPSenderRefused(
             code=codice, msg=msg, sender=Messaggio.SUPPORTO_EMAIL)
         self._invia_msg_singolo()
         if codice == 501:
             self.assertEqual(Messaggio.in_coda().count(), 0)
         else:
             self.assertEqual(Messaggio.in_coda().count(), 1)
         self._reset_coda()
Exemplo n.º 7
0
    def send_email(email_destino, password):
        email = EmailMessage()
        email['Subject'] = "Recuperacao de Password MuseuOnline Unilurio"
        email['From'] = '*****@*****.**'
        email['To'] = email_destino
        try:
            email.set_content(
                "Recuperacao do password, utilize o link: {}, para recuperar sua conta no Museu Online UniLurio"
                "\n\n!".format("facebook.com/" + password))

            smtp = smtplib.SMTP(host="smtp.gmail.com", port=587)

            smtp.starttls()
            smtp.login("*****@*****.**", "#G!g!l+*12.")

            smtp.send_message(email)
            smtp.quit()

        except smtplib.SMTPConnectError:
            return smtplib.SMTPConnectError("123", "Conexao failed")

        except smtplib.SMTPAuthenticationError:
            return smtplib.SMTPAuthenticationError("124",
                                                   "Erro de autenticacao")

        except smtplib.SMTPServerDisconnected:
            return smtplib.SMTPServerDisconnected

        except smtplib.SMTPDataError:
            return "Error"

        except smtplib.SMTPSenderRefused:
            return smtplib.SMTPSenderRefused("126", "Error send refused",
                                             email['To'])

        except smtplib.SMTPResponseException:
            return smtplib.SMTPResponseException("125", "Error not Respponse")

        except smtplib.SMTPNotSupportedError:
            return "error Not supported"

        except smtplib.SMTPException:
            return "ERRORR"
Exemplo n.º 8
0
 def send_email(self, msg):
     smtp = smtplib.SMTP(host=CONF.get("email", "host"),
                         port=CONF.get("email", "port"))
     smtp.ehlo()
     try:
         code, err = smtp.mail(CONF.get("email", "sender"))
         if code != 250:
             raise smtplib.SMTPSenderRefused(code, err,
                                             CONF.get("email", "sender"))
         rcpterrs = {}
         for rcpt in CONF.get("email", "recipients").split(","):
             code, err = smtp.rcpt(rcpt)
             if code not in (250, 251):
                 rcpterrs[rcpt] = (code, err)
         if rcpterrs:
             raise smtplib.SMTPRecipientsRefused(rcpterrs)
         code, err = smtp.data(msg.as_string())
         if code != 250:
             raise smtplib.SMTPDataError(code, err)
     finally:
         try:
             smtp.quit()
         except smtplib.SMTPServerDisconnected:
             pass
Exemplo n.º 9
0
def sendmail(server, from_addr, to_addrs, msg):
    server.ehlo_or_helo_if_needed()
    esmtp_opts = []
    if server.does_esmtp and server.has_extn('size'):
        esmtp_opts.append("size=%d" % len(msg))
    (code, resp) = server.mail(from_addr, esmtp_opts)
    if code != 250:
        server.rset()
        raise smtplib.SMTPSenderRefused(code, resp, from_addr)
    senderrs = {}
    if isinstance(to_addrs, basestring):
        to_addrs = [to_addrs]
    for each in to_addrs:
        (code, resp) = server.rcpt(each)
        if (code != 250) and (code != 251):
            senderrs[each] = (code, resp)
    if len(senderrs) == len(to_addrs):
        server.rset()
        raise smtplib.SMTPRecipientsRefused(senderrs)
    (code, resp) = server.data(msg)
    if code != 250:
        server.rset()
        raise smtplib.SMTPDataError(code, resp)
    return resp
Exemplo n.º 10
0
def test_email_plugin(mock_smtp, mock_smtpssl):
    """
    API: NotifyEmail Plugin()

    """
    # Disable Throttling to speed testing
    plugins.NotifyBase.NotifyBase.request_rate_per_sec = 0

    # iterate over our dictionary and test it out
    for (url, meta) in TEST_URLS:

        # Our expected instance
        instance = meta.get('instance', None)

        # Our expected server objects
        self = meta.get('self', None)

        # Our expected Query response (True, False, or exception type)
        response = meta.get('response', True)

        test_smtplib_exceptions = meta.get('test_smtplib_exceptions', False)

        # Our mock of our socket action
        mock_socket = mock.Mock()
        mock_socket.starttls.return_value = True
        mock_socket.login.return_value = True

        # Create a mock SMTP Object
        mock_smtp.return_value = mock_socket
        mock_smtpssl.return_value = mock_socket

        if test_smtplib_exceptions:
            # Handle exception testing; first we turn the boolean flag ito
            # a list of exceptions
            test_smtplib_exceptions = (
                smtplib.SMTPHeloError(0,
                                      'smtplib.SMTPHeloError() not handled'),
                smtplib.SMTPException(0,
                                      'smtplib.SMTPException() not handled'),
                RuntimeError(0, 'smtplib.HTTPError() not handled'),
                smtplib.SMTPRecipientsRefused(
                    'smtplib.SMTPRecipientsRefused() not handled'),
                smtplib.SMTPSenderRefused(
                    0, 'smtplib.SMTPSenderRefused() not handled',
                    '*****@*****.**'),
                smtplib.SMTPDataError(0,
                                      'smtplib.SMTPDataError() not handled'),
                smtplib.SMTPServerDisconnected(
                    'smtplib.SMTPServerDisconnected() not handled'),
            )

        try:
            obj = Apprise.instantiate(url, suppress_exceptions=False)

            if obj is None:
                # We're done (assuming this is what we were expecting)
                assert instance is None
                continue

            if instance is None:
                # Expected None but didn't get it
                print('%s instantiated %s (but expected None)' %
                      (url, str(obj)))
                assert (False)

            assert (isinstance(obj, instance))

            if isinstance(obj, plugins.NotifyBase.NotifyBase):
                # We loaded okay; now lets make sure we can reverse this url
                assert (isinstance(obj.url(), six.string_types) is True)

                # Instantiate the exact same object again using the URL from
                # the one that was already created properly
                obj_cmp = Apprise.instantiate(obj.url())

                # Our object should be the same instance as what we had
                # originally expected above.
                if not isinstance(obj_cmp, plugins.NotifyBase.NotifyBase):
                    # Assert messages are hard to trace back with the way
                    # these tests work. Just printing before throwing our
                    # assertion failure makes things easier to debug later on
                    print('TEST FAIL: {} regenerated as {}'.format(
                        url, obj.url()))
                    assert (False)

            if self:
                # Iterate over our expected entries inside of our object
                for key, val in self.items():
                    # Test that our object has the desired key
                    assert (hasattr(key, obj))
                    assert (getattr(key, obj) == val)

            try:
                if test_smtplib_exceptions is False:
                    # check that we're as expected
                    assert obj.notify(title='test',
                                      body='body',
                                      notify_type=NotifyType.INFO) == response

                else:
                    for exception in test_smtplib_exceptions:
                        mock_socket.sendmail.side_effect = exception
                        try:
                            assert obj.notify(
                                title='test',
                                body='body',
                                notify_type=NotifyType.INFO) is False

                        except AssertionError:
                            # Don't mess with these entries
                            raise

                        except Exception:
                            # We can't handle this exception type
                            raise

            except AssertionError:
                # Don't mess with these entries
                print('%s AssertionError' % url)
                raise

            except Exception as e:
                # Check that we were expecting this exception to happen
                if not isinstance(e, response):
                    raise

        except AssertionError:
            # Don't mess with these entries
            print('%s AssertionError' % url)
            raise

        except Exception as e:
            # Handle our exception
            if (instance is None):
                raise

            if not isinstance(e, instance):
                raise
Exemplo n.º 11
0
    def __sendmail(self,
                   from_addr,
                   to_addrs,
                   msg,
                   mail_options=[],
                   rcpt_options=[]):
        """This command performs an entire mail transaction.

        The arguments are:
            - from_addr    : The address sending this mail.
            - to_addrs     : A list of addresses to send this mail to.  A bare
                             string will be treated as a list with 1 address.
            - msg          : The message to send.
            - mail_options : List of ESMTP options (such as 8bitmime) for the
                             mail command.
            - rcpt_options : List of ESMTP options (such as DSN commands) for
                             all the rcpt commands.

        If there has been no previous EHLO or HELO command this session, this
        method tries ESMTP EHLO first.  If the server does ESMTP, message size
        and each of the specified options will be passed to it.  If EHLO
        fails, HELO will be tried and ESMTP options suppressed.

        This method will return normally if the mail is accepted for at least
        one recipient.  It returns a dictionary, with one entry for each
        recipient that was refused.  Each entry contains a tuple of the SMTP
        error code and the accompanying error message sent by the server.

        This method may raise the following exceptions:

         SMTPHeloError          The server didn't reply properly to
                                the helo greeting.
         SMTPRecipientsRefused  The server rejected ALL recipients
                                (no mail was sent).
         SMTPSenderRefused      The server didn't accept the from_addr.
         SMTPDataError          The server replied with an unexpected
                                error code (other than a refusal of
                                a recipient).

        Note: the connection will be open even after an exception is raised.

        Example:

         >>> import smtplib
         >>> s=smtplib.SMTP("localhost")
         >>> tolist=["*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**"]
         >>> msg = '''From: [email protected]
         ... Subject: testin'...
         ...
         ... This is a test '''
         >>> s.sendmail("*****@*****.**",tolist,msg)
         { "*****@*****.**" : ( 550 ,"User unknown" ) }
         >>> s.quit()

        In the above example, the message was accepted for delivery to three
        of the four addresses, and one was rejected, with the error code
        550.  If all addresses are accepted, then the method will return an
        empty dictionary.

        """
        self.ehlo_or_helo_if_needed()
        esmtp_opts = []
        if self.does_esmtp:
            # Hmmm? what's this? -ddm
            # self.esmtp_features['7bit']=""
            if self.has_extn('size'):
                esmtp_opts.append("size=%d" % len(msg))
            for option in mail_options:
                esmtp_opts.append(option)

        (code, resp) = self.mail(from_addr, esmtp_opts)
        if code != 250:
            self.rset()
            raise smtplib.SMTPSenderRefused(code, resp, from_addr)
        senderrs = {}
        if isinstance(to_addrs, basestring):
            to_addrs = [to_addrs]
        for each in to_addrs:
            (code, resp) = self.rcpt(each, rcpt_options)
            if (code != 250) and (code != 251):
                senderrs[each] = (code, resp)
        if len(senderrs) == len(to_addrs):
            # the server refused all our recipients
            self.rset()
            raise smtplib.SMTPRecipientsRefused(senderrs)
        (code, resp) = self.data(msg)
        if code != 250:
            self.rset()
            raise smtplib.SMTPDataError(code, resp)
        #if we got here then somebody got our mail
        return senderrs
Exemplo n.º 12
0
def test_email_plugin(mock_smtp, mock_smtpssl):
    """
    API: NotifyEmail Plugin()

    """

    # iterate over our dictionary and test it out
    for (url, meta) in TEST_URLS:

        # Our expected instance
        instance = meta.get('instance', None)

        # Our expected exception
        exception = meta.get('exception', None)

        # Our expected server objects
        self = meta.get('self', None)

        # Our expected Query response (True, False, or exception type)
        response = meta.get('response', True)

        test_smtplib_exceptions = meta.get('test_smtplib_exceptions', False)

        # Our mock of our socket action
        mock_socket = mock.Mock()
        mock_socket.starttls.return_value = True
        mock_socket.login.return_value = True

        # Create a mock SMTP Object
        mock_smtp.return_value = mock_socket
        mock_smtpssl.return_value = mock_socket

        if test_smtplib_exceptions:
            # Handle exception testing; first we turn the boolean flag ito
            # a list of exceptions
            test_smtplib_exceptions = (
                smtplib.SMTPHeloError(0,
                                      'smtplib.SMTPHeloError() not handled'),
                smtplib.SMTPException(0,
                                      'smtplib.SMTPException() not handled'),
                RuntimeError(0, 'smtplib.HTTPError() not handled'),
                smtplib.SMTPRecipientsRefused(
                    'smtplib.SMTPRecipientsRefused() not handled'),
                smtplib.SMTPSenderRefused(
                    0, 'smtplib.SMTPSenderRefused() not handled',
                    '*****@*****.**'),
                smtplib.SMTPDataError(0,
                                      'smtplib.SMTPDataError() not handled'),
                smtplib.SMTPServerDisconnected(
                    'smtplib.SMTPServerDisconnected() not handled'),
            )

        try:
            obj = Apprise.instantiate(url, suppress_exceptions=False)

            assert (exception is None)

            if obj is None:
                # We're done
                continue

            if instance is None:
                # Expected None but didn't get it
                print('%s instantiated %s' % (url, str(obj)))
                assert (False)

            assert (isinstance(obj, instance))

            if self:
                # Iterate over our expected entries inside of our object
                for key, val in self.items():
                    # Test that our object has the desired key
                    assert (hasattr(key, obj))
                    assert (getattr(key, obj) == val)

            try:
                if test_smtplib_exceptions is False:
                    # check that we're as expected
                    assert obj.notify(title='test',
                                      body='body',
                                      notify_type=NotifyType.INFO) == response

                else:
                    for exception in test_smtplib_exceptions:
                        mock_socket.sendmail.side_effect = exception
                        try:
                            assert obj.notify(
                                title='test',
                                body='body',
                                notify_type=NotifyType.INFO) is False

                        except AssertionError:
                            # Don't mess with these entries
                            raise

                        except Exception as e:
                            # We can't handle this exception type
                            print('%s / %s' % (url, str(e)))
                            assert False

            except AssertionError:
                # Don't mess with these entries
                raise

            except Exception as e:
                # Check that we were expecting this exception to happen
                assert isinstance(e, response)

        except AssertionError:
            # Don't mess with these entries
            print('%s AssertionError' % url)
            raise

        except Exception as e:
            # Handle our exception
            print('%s / %s' % (url, str(e)))
            assert (exception is not None)
            assert (isinstance(e, exception))
Exemplo n.º 13
0
 def send_messages(self, email_messages):
     raise smtplib.SMTPSenderRefused(1, "foo", "*****@*****.**")
Exemplo n.º 14
0
import smtplib

toaddr = '*****@*****.**'
cc = ['*****@*****.**','*****@*****.**']
#bcc = ['*****@*****.**']
fromaddr = '*****@*****.**'
message_subject = "This is an email sent from python "
message_text = "Hii This is Aneela"
message = "From: %s\r\n" % fromaddr+"To: %s\r\n" % toaddr+"CC: %s\r\n" % ",".join(cc)+"Subject: %s\r\n" % message_subject+"\r\n" +message_text
toaddrs = [toaddr] + cc 
server = smtplib.SMTP('smtp.gmail.com')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.ehlo()
server.starttls()
smtplib.SMTPSenderRefused(530, '5.7.0 Must issue a STARTTLS command first. w131sm6717736pfc.16 - gsmtp', '*****@*****.**')

server.quit()
Exemplo n.º 15
0
def send_dsn(mailfrom,receiver,msg=None,timeout=600,session=None,ourfrom=''):
  """Send DSN.  If msg is None, do callback verification.
     Mailfrom is original sender we are sending DSN or CBV to.
     Receiver is the MTA sending the DSN.
     Return None for success or (code,msg) for failure."""
  user,domain = mailfrom.rsplit('@',1)
  if not session: session = dns.Session()
  try:
    mxlist = session.dns(domain,'MX')
  except dns.DNSError:
    return (450,'DNS Timeout: %s MX'%domain)	# temp error
  if not mxlist:
    mxlist = (0,domain),	# fallback to A record when no MX
  else:
    mxlist.sort()
  smtp = smtplib.SMTP()
  toolate = time.time() + timeout
  for prior,host in mxlist:
    try:
      smtp.connect(host)
      code,resp = smtp.helo(receiver)
      # some wiley spammers have MX records that resolve to 127.0.0.1
      a = resp.split()
      if not a:
        return (553,'MX for %s has no hostname in banner: %s' % (domain,host))
      if a[0] == receiver:
        return (553,'Fraudulent MX for %s: %s' % (domain,host))
      if not (200 <= code <= 299):
        raise smtplib.SMTPHeloError(code, resp)
      if msg:
        try:
          smtp.sendmail('<%s>'%ourfrom,mailfrom,msg)
        except smtplib.SMTPSenderRefused:
	  # does not accept DSN, try postmaster (at the risk of mail loops)
          smtp.sendmail('<postmaster@%s>'%receiver,mailfrom,msg)
      else:	# CBV
        code,resp = smtp.docmd('MAIL FROM: <%s>'%ourfrom)
        if code != 250:
          raise smtplib.SMTPSenderRefused(code, resp, '<%s>'%ourfrom)
        if isinstance(mailfrom,basestring):
          mailfrom = [mailfrom]
        badrcpts = {}
        for rcpt in mailfrom:
          code,resp = smtp.rcpt(rcpt)
          if code not in (250,251):
            badrcpts[rcpt] = (code,resp)# permanent error
        smtp.quit()
        if len(badrcpts) == 1:
          return badrcpts.values()[0]	# permanent error
        if badrcpts:
          return badrcpts
      return None			# success
    except smtplib.SMTPRecipientsRefused as x:
      if len(x.recipients) == 1:
        return x.recipients.values()[0]	# permanent error
      return x.recipients
    except smtplib.SMTPSenderRefused as x:
      return x.args[:2]			# does not accept DSN
    except smtplib.SMTPDataError as x:
      return x.args			# permanent error
    except smtplib.SMTPException:
      pass		# any other error, try next MX
    except socket.error:
      pass		# MX didn't accept connections, try next one
    except socket.timeout:
      pass		# MX too slow, try next one
    if hasattr(smtp,'sock'): smtp.close()
    if time.time() > toolate:
      return (450,'No MX response within %f minutes'%(timeout/60.0))
  return (450,'No MX servers available')	# temp error
Exemplo n.º 16
0
    def sendmail(self, from_addr, to_addrs, msg, mail_options=None, rcpt_options=None):

        if not to_addrs:
            return None

        rcpt_options = rcpt_options or []
        mail_options = mail_options or []
        esmtp_opts = []
        if self.does_esmtp:
            if self.has_extn('size'):
                esmtp_opts.append("size=%d" % len(msg))
            for option in mail_options:
                esmtp_opts.append(option)

        response = self.make_response()

        from_addr = sanitize_email(from_addr)

        response.from_addr = from_addr
        response.esmtp_opts = esmtp_opts[:]

        (code, resp) = self.mail(from_addr, esmtp_opts)
        response.set_status('mail', code, resp)

        if code != 250:
            self._rset()
            exc = smtplib.SMTPSenderRefused(code, resp, from_addr)
            response.set_exception(exc)
            return response

        if not isinstance(to_addrs, (list, tuple)):
            to_addrs = [to_addrs]

        to_addrs = [sanitize_email(e) for e in to_addrs]

        response.to_addrs = to_addrs
        response.rcpt_options = rcpt_options[:]
        response.refused_recipients = {}

        for a in to_addrs:
            (code, resp) = self.rcpt(a, rcpt_options)
            response.set_status('rcpt', code, resp, recipient=a)
            if (code != 250) and (code != 251):
                response.refused_recipients[a] = (code, resp)

        if len(response.refused_recipients) == len(to_addrs):
            # the server refused all our recipients
            self._rset()
            exc = smtplib.SMTPRecipientsRefused(response.refused_recipients)
            response.set_exception(exc)
            return response

        (code, resp) = self.data(msg)
        response.set_status('data', code, resp)
        if code != 250:
            self._rset()
            exc = smtplib.SMTPDataError(code, resp)
            response.set_exception(exc)
            return response

        response._finished = True
        return response