Exemple #1
0
def test_sendmail_onerror():
    from_addr = '*****@*****.**'
    to_addresses = ['*****@*****.**', '*****@*****.**']
    msg_as_string = 'test mail content'
    msg_size_exceed = "A" * 1200
    result = e3.net.smtp.sendmail(from_addr,
                                  to_addresses,
                                  msg_size_exceed, ['smtp.localhost'],
                                  max_size=8 / 1024)
    assert result is False

    with mock.patch('smtplib.SMTP') as mock_smtp:
        mock_smtp.side_effect = smtplib.SMTPException()
        result = e3.net.smtp.sendmail(from_addr, to_addresses, msg_as_string,
                                      ['smtp.localhost'])
        assert result is False

    with mock.patch('smtplib.SMTP') as mock_smtp:
        smtp_mock = mock_smtp.return_value
        smtp_mock.sendmail.side_effect = smtplib.SMTPException()
        result = e3.net.smtp.sendmail(from_addr, to_addresses, msg_as_string,
                                      ['smtp.localhost'])
        assert result is False

    with mock.patch('smtplib.SMTP') as mock_smtp:
        smtp_mock = mock_smtp.return_value
        smtp_mock.sendmail.return_value = {}
        result = e3.net.smtp.sendmail(from_addr, to_addresses, msg_as_string,
                                      ['smtp.localhost'])
        assert result is True
Exemple #2
0
    def _connect_to_exchange(self, smtp):
        code, response = smtp.ehlo()
        if code != SMTP_EHLO_OKAY:
            logging.error("Server did not respond as expected to EHLO command")
            raise smtplib.SMTPException(
                "Server did not respond as expected to EHLO command")
        sspiclient = sspi.ClientAuth('NTLM')

        # Generate the NTLM Type 1 message
        sec_buffer = None
        err, sec_buffer = sspiclient.authorize(sec_buffer)
        ntlm_message = asbase64(sec_buffer[0].Buffer)

        # Send the NTLM Type 1 message -- Authentication Request
        code, response = smtp.docmd("AUTH", "NTLM " + ntlm_message)

        # Verify the NTLM Type 2 response -- Challenge Message
        if code != SMTP_AUTH_CHALLENGE:
            logging.error(
                "Server did not respond as expected to NTLM negotiate message")
            raise smtplib.SMTPException(
                "Server did not respond as expected to NTLM negotiate message")

        # Generate the NTLM Type 3 message
        err, sec_buffer = sspiclient.authorize(base64.decodebytes(response))
        ntlm_message = asbase64(sec_buffer[0].Buffer)

        # Send the NTLM Type 3 message -- Response Message
        code, response = smtp.docmd("", ntlm_message)
        if code != SMTP_AUTH_OKAY:
            logging.error("SMTPAuthenticationError")
            raise smtplib.SMTPAuthenticationError(code, response)
        # if this part is reached, the authentication was succesfull and emails can be sent.
        pass
Exemple #3
0
def test_sendmail_onerror(caplog):
    from_addr = "*****@*****.**"
    to_addresses = ["*****@*****.**", "*****@*****.**"]
    msg_as_string = "test mail content"
    msg_size_exceed = "A" * 1200
    result = e3.net.smtp.sendmail(from_addr,
                                  to_addresses,
                                  msg_size_exceed, ["smtp.localhost"],
                                  max_size=1 / 1024)
    assert result is False
    assert "message file too big" in caplog.text

    with mock.patch("smtplib.SMTP_SSL") as mock_smtp:
        mock_smtp.side_effect = smtplib.SMTPException()
        result = e3.net.smtp.sendmail(from_addr, to_addresses, msg_as_string,
                                      ["smtp.localhost"])
        assert result is False

    with mock.patch("smtplib.SMTP_SSL") as mock_smtp:
        smtp_mock = mock_smtp.return_value
        smtp_mock.sendmail.side_effect = smtplib.SMTPException()
        result = e3.net.smtp.sendmail(from_addr, to_addresses, msg_as_string,
                                      ["smtp.localhost"])
        assert result is False

    with mock.patch("smtplib.SMTP_SSL") as mock_smtp:
        smtp_mock = mock_smtp.return_value
        smtp_mock.sendmail.return_value = {}

        mid = make_msgid()
        result = e3.net.smtp.sendmail(from_addr,
                                      to_addresses,
                                      msg_as_string, ["smtp.localhost"],
                                      message_id=mid)
        assert result is True
        assert "Message-ID: %s sent successfully" % mid in caplog.text
        assert "smtp quit" in caplog.text

    with mock.patch("smtplib.SMTP_SSL") as mock_smtp:
        smtp_mock = mock_smtp.return_value
        smtp_mock.sendmail.return_value = {}

        def error_on_quit():
            raise smtplib.SMTPException("error on quit ignored")

        smtp_mock.quit = error_on_quit
        mid = make_msgid()
        result = e3.net.smtp.sendmail(from_addr,
                                      to_addresses,
                                      msg_as_string, ["smtp.localhost"],
                                      message_id=mid)
        assert result is True
        assert "Message-ID: %s sent successfully" % mid in caplog.text
    def login(self, user, password):
        def encode_cram_md5(challenge, user, password):
            challenge = encode_base64.decodestring(challenge)
            response = user + " " + smtplib.hmac.HMAC(password,
                                                      challenge).hexdigest()
            return encode_base64(response)

        def encode_plain(user, password):
            s = "\0%s\0%s" % (user, password)
            return encode_base64(s.encode('ascii'), eol='')

        AUTH_PLAIN = "PLAIN"
        AUTH_CRAM_MD5 = "CRAM-MD5"
        AUTH_LOGIN = "******"

        self.ehlo_or_helo_if_needed()

        if not self.has_extn("auth"):
            raise smtplib.SMTPException(
                "SMTP AUTH extension not supported by server.")

        authlist = self.esmtp_features["auth"].split()
        preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN]

        authmethod = None
        for method in preferred_auths:
            if method in authlist:
                authmethod = method
                break

        if authmethod == AUTH_LOGIN:
            (code,
             resp) = self.docmd("AUTH",
                                "%s %s" % (AUTH_LOGIN, encode_base64(user)))
            if code != 334:
                raise smtplib.SMTPAuthenticationError(code, resp)
            (code, resp) = self.docmd(encode_base64(password))
        elif authmethod == AUTH_PLAIN:
            temp_encode_plain = str(encode_plain(user, password))
            temp_encode_plain = temp_encode_plain.replace("\n", "")
            (code, resp) = self.docmd("AUTH",
                                      AUTH_PLAIN + " " + temp_encode_plain)
        elif authmethod == AUTH_CRAM_MD5:
            (code, resp) = self.docmd("AUTH", AUTH_CRAM_MD5)
            if code == 503:
                return (code, resp)
            (code, resp) = self.docmd(encode_cram_md5(resp, user, password))
        elif authmethod is None:
            raise smtplib.SMTPException(
                "No suitable authentication method found.")
        if code not in (235, 503):
            raise smtplib.SMTPAuthenticationError(code, resp)
        return (code, resp)
Exemple #5
0
def test_sendmail_onerror(caplog):
    from_addr = '*****@*****.**'
    to_addresses = ['*****@*****.**', '*****@*****.**']
    msg_as_string = 'test mail content'
    msg_size_exceed = "A" * 1200
    result = e3.net.smtp.sendmail(from_addr,
                                  to_addresses,
                                  msg_size_exceed, ['smtp.localhost'],
                                  max_size=1 / 1024)
    assert result is False
    assert 'message file too big' in caplog.text

    with mock.patch('smtplib.SMTP_SSL') as mock_smtp:
        mock_smtp.side_effect = smtplib.SMTPException()
        result = e3.net.smtp.sendmail(from_addr, to_addresses, msg_as_string,
                                      ['smtp.localhost'])
        assert result is False

    with mock.patch('smtplib.SMTP_SSL') as mock_smtp:
        smtp_mock = mock_smtp.return_value
        smtp_mock.sendmail.side_effect = smtplib.SMTPException()
        result = e3.net.smtp.sendmail(from_addr, to_addresses, msg_as_string,
                                      ['smtp.localhost'])
        assert result is False

    with mock.patch('smtplib.SMTP_SSL') as mock_smtp:
        smtp_mock = mock_smtp.return_value
        smtp_mock.sendmail.return_value = {}

        mid = make_msgid()
        result = e3.net.smtp.sendmail(from_addr,
                                      to_addresses,
                                      msg_as_string, ['smtp.localhost'],
                                      message_id=mid)
        assert result is True
        assert 'Message-ID: %s sent successfully' % mid in caplog.text
        assert 'smtp quit' in caplog.text

    with mock.patch('smtplib.SMTP_SSL') as mock_smtp:
        smtp_mock = mock_smtp.return_value
        smtp_mock.sendmail.return_value = {}

        def error_on_quit():
            raise smtplib.SMTPException('error on quit ignored')

        smtp_mock.quit = error_on_quit
        mid = make_msgid()
        result = e3.net.smtp.sendmail(from_addr,
                                      to_addresses,
                                      msg_as_string, ['smtp.localhost'],
                                      message_id=mid)
        assert result is True
        assert 'Message-ID: %s sent successfully' % mid in caplog.text
def ntlm_authenticate(smtp, username, password):
    code, response = smtp.docmd(
        "AUTH", "NTLM " + ntlm.create_NTLM_NEGOTIATE_MESSAGE(username))
    if code != 334:
        raise smtplib.SMTPException(
            "Server did not respond as expected to NTLM negotiate message")
    challenge, flags = ntlm.parse_NTLM_CHALLENGE_MESSAGE(response)
    user_parts = username.split("\\", 1)
    code, response = smtp.docmd(
        "",
        ntlm.create_NTLM_AUTHENTICATE_MESSAGE(challenge, user_parts[1],
                                              user_parts[0], password, flags))
    if code != 235:
        raise smtplib.SMTPException(code, response)
Exemple #7
0
    def login(self, username, password):
        def encode_cram_md5(challenge, username, password): 
            challenge = base64.decodebytes(challenge)
            response = username + " " + hmac.HMAC(password.encode('ascii'), challenge, 'md5').hexdigest()
            return encode_base64(response.encode('ascii'), eol="")

        def encode_plain(user, password): 
            return encode_base64(("\0%s\0%s" % (user, password)).encode('ascii'), eol="")

        AUTH_PLAIN = "PLAIN"
        AUTH_CRAM_MD5 = "CRAM-MD5"
        AUTH_LOGIN = "******"

        yield self.ehlo_or_helo_if_needed()
        if not self.has_extn('auth'):
            raise smtplib.SMTPException("SMTP Auth extension not supported by server ")

        advertised_authlist = self.esmtp_features["auth"].split()

        preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN]

        authlist = [auth for auth in preferred_auths if auth in advertised_authlist]
        if not authlist:
            raise smtplib.SMTPException("No suitable authentication method found.")

        # Some servers advertise authentication methods they don't really
        # support, so if authentication fails, we continue until we've tried
        # all methods.
        for authmethod in authlist:
            if authmethod == AUTH_CRAM_MD5:
                (code, resp) = yield self.docmd(b'AUTH', AUTH_CRAM_MD5)
                if code == 334:
                    (code, resp) =yield self.docmd(encode_cram_md5(resp, username, password).encode('ascii'))
            elif authmethod == AUTH_PLAIN:
                (code, resp) =yield self.docmd(b'AUTH',
                 (AUTH_PLAIN + " " + encode_plain(username, password)).encode('ascii'))
            elif authmethod == AUTH_LOGIN:
                (code, resp) = yield self.docmd(b'AUTH',
                ("%s %s" % (AUTH_LOGIN, encode_base64(username.encode('ascii'), eol=''))).encode('ascii'))
                if code == 334:
                    (code, resp) = yield self.docmd(encode_base64(password.encode('ascii'), eol='').encode('ascii'))

            # 235 == 'Authentication successful'
            # 503 == 'Error: already authenticated'
            if code in (235, 503):
                raise gen.Return((code, resp))

        # We could not login sucessfully. Return result of last attempt.
        raise smtplib.SMTPAuthenticationError(code, resp)
Exemple #8
0
    def verify_pass(self):
        '''Verify the password we got works for SMTPAUTH.'''
        try:
            smtp = smtplib.SMTP(self.host, self.port)
        except socket.error as msg:
            raise MailSendError(msg)

        # NOTE WELL: SECURITY IMPORTANT NOTE!
        # In python 2.6 if you attempt to starttls() and the server doesn't
        # understand an exception is raised. However before that, it just carried on
        # and one could attempt to auth over a plain-text session. This is BAD!
        #
        # So, in order be secure on older pythons we ehlo() and then check the
        # response before attempting startls.
        try:
            smtp.ehlo()
            if not smtp.has_extn('STARTTLS'):
                # Emulate 2.6 behavior
                raise smtplib.SMTPException('Server does not support STARTTLS')
            smtp.starttls()
            # must ehlo after startls
            smtp.ehlo()
            smtp.login(self.user, self.password)
        except smtplib.SMTPAuthenticationError:
            return False
        except (smtplib.SMTPException, socket.error) as msg:
            raise MailSendError(msg)
        finally:
            smtp.quit()

        return True
Exemple #9
0
def send_email(to_email, subject, msg):
  rcinfo = netrc.netrc(os.path.expanduser('~/.netrc'))
  auth = rcinfo.authenticators('gmail')
  email = auth[0]
  name = auth[1].replace('+', ' ')  # put a + for space in the .netrc file
  password = auth[2]
  server = 'smtp.gmail.com'
  port = 587
  LOG.info('Connecting to %s:%s', server, port)
  server = smtplib.SMTP(server, port)
  server.ehlo()
  server.starttls()
  server.ehlo()
  LOG.info('Logging in using email %s', email)
  server.login(email, password)
  full_message = ['To: %s' % to_email,
      'From: %s <%s>' % (name, email),
      'Reply-To: %s' % to_email,
      'Subject: %s' % subject,
      '',
      msg]
  LOG.info('Full Message\n%s', '\n'.join(full_message))
  result = server.sendmail(email, to_email, '\n'.join(full_message))
  if result:
    errs = []
    for recip in result:
      errs.append(
          'Could not deliver mail to: %s\n'
          'Server said: %s\n%s' % (recip, result[recip][0], result[recip][1]))
    raise smtplib.SMTPException('\n'.join(errs))
  server.close()
Exemple #10
0
    def sendmail(self, from_addr, to_addrs, msg, mail_options=()):
        """invoke sendmail program to send a message.
        `from_addr' is envelope sender string (may be empty)
        `to_addrs' is list of envelope recipient addresses
        `msg' is headers and body of message to be sent
        `mail_options' is list of options ('8bitmime')"""

        cmd = [self.SENDMAIL]
        if from_addr:
            cmd.append('-f%s' % from_addr)
        if '8bitmime' in mail_options:
            cmd.append('-B8BITMIME')
        # avoid shell / quoting issues
        proc = subprocess.Popen(cmd + to_addrs,
                                shell=False,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        proc.stdin.write(msg.replace('\n.\n', '\n..\n'))
        proc.stdin.close()
        ret = proc.wait()
        out = proc.stdout.readlines()
        err = proc.stderr.readlines()

        if self.debug:
            for line in out:
                print("stdout:", line)
            for line in err:
                print("stderr:", line)

        # complain if out or error are non-empty?
        if ret != OS_OK:
            raise smtplib.SMTPException()
        return {}
Exemple #11
0
def test_smtp_sendmail_error(mock_getpass, mock_SMTP_SSL, tmp_path):
    """Failure during SMTP protocol."""
    # Config for SSL SMTP server
    config_path = tmp_path/"server.conf"
    config_path.write_text(textwrap.dedent(u"""\
        [smtp_server]
        host = smtp.gmail.com
        port = 465
        security = SSL/TLS
        username = awdeorio
    """))

    # Simple template
    sendmail_client = SendmailClient(config_path, dry_run=False)
    message = email.message_from_string(u"Hello world")

    # Mock the password entry
    mock_getpass.return_value = "password"

    # Configure SMTP sendmail() to raise an exception
    mock_SMTP_SSL.return_value.__enter__.return_value.sendmail = mock.Mock(
        side_effect=smtplib.SMTPException("Dummy error message")
    )

    # Send a message
    with pytest.raises(MailmergeError) as err:
        sendmail_client.sendmail(
            sender="*****@*****.**",
            recipients=["*****@*****.**"],
            message=message,
        )

    # Verify exception string
    assert "Dummy error message" in str(err.value)
    def test_error_handling(self):
        # pytest.raises exists: pylint: disable=E1101
        smtp_client_helper = smtp_client.SmtpClientHelper("servername", "80")
        self._smtp_client.sendmail.side_effect = smtplib.SMTPException()

        pytest.raises(smtplib.SMTPException, smtp_client_helper.send_mail,
                      "*****@*****.**", ["*****@*****.**"], "subject", "message")
Exemple #13
0
    def register_authentication(self, sender, recipient):
        chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
        secret_key = get_random_string(self.key_length, chars)

        msg            = MIMEText("Vulture authentication\r\nThis is your secret key: {}".format(secret_key))
        msg['Subject'] = 'Vulture OTP Authentication'
        msg['From']    = sender
        msg['To']      = recipient

        cluster = Cluster.objects.get()
        node = cluster.get_current_node()
        smtp_settings = getattr(node.system_settings, 'smtp_settings')
        if not smtp_settings:
            """ Not found, use cluster settings for configuration """
            smtp_settings = getattr(cluster.system_settings, 'smtp_settings')

        if not smtp_settings:
            logger.error("VultureMailClient::register_authentication: Cluster and Node SMTP settings not configured")
            raise smtplib.SMTPException("Vulture mail service not configured")

        server = smtplib.SMTP(smtp_settings.smtp_server)
        message = "Subject: " + unicode (msg['Subject']) + "\n\n" + unicode (msg)
        server.sendmail(msg['from'], recipient, message)
        server.quit()

        return secret_key
def test_smtplib_init_fail(mock_smtplib):
    """
    API: Test exception handling when calling smtplib.SMTP()

    """

    from apprise.plugins import NotifyEmailBase

    obj = Apprise.instantiate('mailto://*****:*****@gmail.com',
                              suppress_exceptions=False)
    assert (isinstance(obj, plugins.NotifyEmail))

    # Support Exception handling of smtplib.SMTP
    mock_smtplib.side_effect = TypeError('Test')

    try:
        obj.notify(title='test', body='body', notify_type=NotifyType.INFO)

        # We should have thrown an exception
        assert False

    except TypeError:
        # Exception thrown as expected
        assert True

    except Exception:
        # Un-Expected
        assert False

    # A handled and expected exception
    mock_smtplib.side_effect = smtplib.SMTPException('Test')
    assert obj.notify(title='test', body='body',
                      notify_type=NotifyType.INFO) is False
    def test_expecting_general_SMTP_error(self) -> None:
        check = UnitTestSmtpCredentials._create_mocked_method_raising(
            smtplib.SMTPException())
        status, message = UnitTestSmtpCredentials._run_mocked_check(
            self.test_expecting_general_SMTP_error.__name__, check)

        self.assertEqual((status, message),
                         (False, smtpcheck.Messages.GENERAL_SMTP_ERROR.value))
Exemple #16
0
 def test_send_failed(self):
     with patch('django.core.mail.message.EmailMessage.send') as mock_send:
         mock_send.side_effect = smtplib.SMTPException("No server")
         self.bulk.send()
     self.assertEqual(len(mail.outbox),
                      0)  # we mocked the actual send, so...
     bulk = BulkEmail.objects.get(pk=self.bulk.pk)
     self.assertEqual(ERROR, bulk.status)
     self.assertEqual("No server", bulk.error)
Exemple #17
0
    def _send_mail(self, to, msg):
        '''Given a to and Message object, send email.'''
        # We don't duplicate the header logic in the sub functions, we
        # do that here
        debug("send_mail called with to (%s), subject (%s)" %
              (to, msg['subject']))
        if self.display_name:
            msg['From'] = self.display_name + ' <' + self.mail + '>'
        else:
            msg['From'] = self.mail
        if self.address_override:
            msg['To'] = self.address_override
        else:
            msg['To'] = to
        msg['Date'] = formatdate(localtime=True)

        try:
            smtp = smtplib.SMTP(self.host, self.port)
            if self.tls:
                # NOTE WELL: SECURITY IMPORTANT NOTE!
                # In python 2.6 if you attempt to starttls() and the server doesn't
                # understand an exception is raised. However before that, it just
                # carried on and one could attempt to auth over a plain-text session.
                # This is BAD!
                #
                # So, in order be secure on older pythons we ehlo() and then check the
                # response before attempting startls.
                smtp.ehlo()
                if not smtp.has_extn('STARTTLS'):
                    # Emulate 2.6 behavior
                    raise smtplib.SMTPException(
                        'Server does not support STARTTLS')
                smtp.starttls()
                # must re-ehlo after STARTTLS
                smtp.ehlo()
                # Don't want to send auth information unless we're TLS'd
                if self.user:
                    smtp.login(self.user, self.password)
            if self.address_override:
                env_to = self.address_override
            else:
                # BCC the user...
                env_to = [msg['To'], self.mail]

            smtp.sendmail(self.mail, env_to, msg.as_string())
            smtp.quit()
        except smtplib.SMTPException as emsg:
            raise MailSendError(emsg)
        except socket.error as emsg:
            raise MailSendError(emsg)
Exemple #18
0
 def starttls(self, keyfile=None, certfile=None):
     if not self.has_extn("starttls"):
         msg = "STARTTLS extension not supported by server"
         raise smtplib.SMTPException(msg)
     (resp, reply) = self.docmd("STARTTLS")
     if resp == 220:
         self.sock = sslutil.wrapsocket(self.sock, keyfile, certfile,
                                        **self._sslkwargs)
         self.file = smtplib.SSLFakeFile(self.sock)
         self.helo_resp = None
         self.ehlo_resp = None
         self.esmtp_features = {}
         self.does_esmtp = 0
     return (resp, reply)
    def test_wraps_mail_server_exceptions(self, messenger, dummy_mailer,
                                          message):
        import smtplib
        from dallinger.notifications import MessengerError

        dummy_mailer.login.side_effect = smtplib.SMTPException("Boom!")
        with pytest.raises(MessengerError) as ex_info:
            messenger.send(message)
        assert ex_info.match("SMTP error")

        dummy_mailer.login.side_effect = Exception("Boom!")
        with pytest.raises(MessengerError) as ex_info:
            messenger.send(message)
        assert ex_info.match("Unknown error")
    def test_send_fail(self, connection_mock):
        exception = smtplib.SMTPException("Something failed", 101)
        connection_mock.return_value.send_messages.side_effect = exception

        result = toolkit.members.tasks.send_mailout(
            u"The \xa31 Subject!", u"The Body!\nThat will be $1, please\nTa!",
            None)

        # Overall, operation succeeded:
        self.assertEqual((False, 6, "Ok"), result)

        # Check errors are in the report message:
        report = connection_mock.return_value.send_messages.call_args[0][0][0]
        expected = "6 errors:\n" + "\n".join([str(exception)] * 6)
        self.assertIn(expected, report.body)
Exemple #21
0
    def send_mail(self,to_addrs_list = None, content = None, subject = None):
        """发送邮件,功能设计的只能发送纯文本的邮件内容
        :param to_addrs_list: 需要发给的地址,是一个list,每一个邮箱地址是list的一个元素。
        :param content: 邮件的内容,是一个string。
        :param subject: 邮件的主题。
        :return: 无返回内容。
        """
        if to_addrs_list != None:
            to_addrs_str = to_addrs_list[0]
            for index in range(1, len(to_addrs_list),1):
                to_addrs_str = to_addrs_str + ',' + to_addrs_list[index]
            to_addrs = list([to_addrs_str])
        else:
            print 'no Email address to send to!'
            raise smtplib.SMTPException()

        if content != None:
            msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
                % (SENDER_MAIL['sent_from'], ", ".join(to_addrs), subject))
            msg = msg + content
            self.server.sendmail(from_addr=SENDER_MAIL['user'],to_addrs=to_addrs,msg=msg)
        else:
            print 'No content in the email!'
            raise smtplib.SMTPException()
Exemple #22
0
 def starttls(self, keyfile=None, certfile=None):
     if not self.has_extn("starttls"):
         msg = "STARTTLS extension not supported by server"
         raise smtplib.SMTPException(msg)
     (resp, reply) = self.docmd("STARTTLS")
     if resp == 220:
         self.sock = sslutil.wrapsocket(self.sock, keyfile, certfile,
                                        **self._sslkwargs)
         if not util.safehasattr(self.sock, "read"):
             # using httplib.FakeSocket with Python 2.5.x or earlier
             self.sock.read = self.sock.recv
         self.file = smtplib.SSLFakeFile(self.sock)
         self.helo_resp = None
         self.ehlo_resp = None
         self.esmtp_features = {}
         self.does_esmtp = 0
     return (resp, reply)
Exemple #23
0
    def starttls(self):
        #TODO: check how to read the local computer name
        yield self.ehlo_or_helo_if_needed() 
        if not self.has_extn('starttls'): 
            raise smtplib.SMTPException('STARTTLS extension not supported ')

        code, msg = yield self.docmd(b'STARTTLS')
        if code == 220: 
            if not _have_ssl: 
                raise RuntimeError("No SSL support included in this Python ")

            server_hostname = self.host if hasattr(ssl, 'HAS_SNI') and ssl.HAS_SNI else None
            self.stream = yield self.stream.start_tls(False, server_hostname = server_hostname)
            self.helo_resp = None 
            self.ehlo_resp = None 
            self.esmtp_features = {}
            self.does_esmtp = 0 
        raise gen.Return((code, msg))
Exemple #24
0
    def process_message(self, peer, mailfrom, rcpttos, data):
        """Handle incoming message"""

        if '*****@*****.**' in rcpttos:
            raise smtplib.SMTPException('Server crashed, try again')

        try:
            with open('message.json') as fh:
                email_list = json.loads(fh.read())
        except IOError:  # File does not yet exist, new list
            email_list = []

        email_list.append(
            dict(origin=peer, sender=mailfrom, receiver=rcpttos,
                 contents=data))

        with open('message.json', 'wb') as fh:
            fh.write(json.dumps(email_list))
Exemple #25
0
    def connect(cls):
        """Connect or reconnect if a connection has timed out"""
        def reconnect():
            if cls.connection is None or cls.connection.noop()[0] == 421:
                return True
            else:
                return False

        count = 0
        for i in range(cls.reconnect_attempts + 1):
            if reconnect():
                count += 1
                cls.connection = cls._connect()
            else:
                break

        if count > cls.reconnect_attempts:
            raise smtplib.SMTPException("Unable to connect")
Exemple #26
0
    def starttls(self, keyfile=None, certfile=None, **sslargs):
        """Puts the connection to the SMTP server into TLS mode.

        If there has been no previous EHLO or HELO command this session, this
        method tries ESMTP EHLO first.

        If the server supports TLS, this will encrypt the rest of the SMTP
        session. If you provide the keyfile and certfile parameters,
        the identity of the SMTP server and client can be checked. This,
        however, depends on whether the socket module really checks the
        certificates.

        :param sslargs: a dict with further SSL arguments, see ssl module (default: {});
        :param ca_certs: PEM formatted file for permitted certificates (default: None), if specified, and the default for cert_reqs is CERT_REQUIRED;

        This method may raise the following exceptions:

         SMTPHeloError            The server didn't reply properly to
                                  the helo greeting.
        """
        import ssl
        self.ehlo_or_helo_if_needed()
        if not self.has_extn("starttls"):
            raise smtplib.SMTPException(
                "STARTTLS extension not supported by server.")
        (resp, reply) = self.docmd("STARTTLS")
        if resp == 220:
            if not sslargs.get('ssl_version'):
                sslargs['ssl_version'] = ssl.PROTOCOL_TLSv1
            if not sslargs.get('cert_reqs'):
                sslargs['cert_reqs'] = ssl.CERT_REQUIRED if sslargs.get(
                    'ca_certs') else ssl.CERT_NONE
            self.sock = ssl.wrap_socket(self.sock, keyfile, certfile,
                                        **sslargs)
            self.file = smtplib.SSLFakeFile(self.sock)
            # RFC 3207:
            # The client MUST discard any knowledge obtained from
            # the server, such as the list of SMTP service extensions,
            # which was not obtained from the TLS negotiation itself.
            self.helo_resp = None
            self.ehlo_resp = None
            self.esmtp_features = {}
            self.does_esmtp = 0
        return (resp, reply)
Exemple #27
0
    def test_do_config_checks_socket_type_errors(self):
        # Set up our mock expectations.
        # Our configuration is using STARTTLS. If we return it supports SSL and
        # it doesn't support STARTTLS, do_config_checks should return 1 error
        # and 1 warning for each server (incoming and outgoing)
        # IMAP SSL
        server = imaplib.IMAP4_SSL('mail.test.com', 993)
        server.capabilities = ('IMAP4REV1', 'SASL-IR', 'SORT',
                'THREAD=REFERENCES', 'MULTIAPPEND',
                'UNSELECT', 'LITERAL+', 'IDLE', 'CHILDREN', 'NAMESPACE',
                'LOGIN-REFERRALS', 'QUOTA', 'AUTH=PLAIN', 'AUTH=LOGIN')
        server.shutdown()
        # IMAP STARTTLS
        server = imaplib.IMAP4('mail.test.com', 995)
        server.starttls().AndRaise(Exception("STARTTLS extension not supported"
                "by server."))
        server.shutdown()
        # SMTP SSL
        server = smtplib.SMTP_SSL('mail.test.com', 465, timeout=TIMEOUT)
        server.ehlo().AndReturn((250,
            'mx2.mail.corp.phx1.test.com\nPIPELINING\nSIZE '
            '31457280\nETRN\nAUTH LOGIN PLAIN NTLM CRAM-MD5 GSSAPI UNSUPPORTED'
            '\nENHANCEDSTATUSCODES\n8BITMIME\nDSN'))
        server.quit()
        # SMTP STARTTLS
        server = smtplib.SMTP('mail.test.com', 465, timeout=TIMEOUT)
        server.ehlo()
        server.starttls().AndRaise(smtplib.SMTPException("STARTTLS extension"
                "not supported by server."))
        server.quit()
        self.mox.ReplayAll()

        #Test methods
        config = Config.objects.get(pk=1)
        config.incoming_socket_type = 'STARTTLS'
        config.outgoing_socket_type = 'STARTTLS'
        config.save()
        errors, warnings = do_config_checks(config)

        # Verify the results (and the mock expectations.)
        self.mox.VerifyAll()
        assert_equal(len(errors), 2)
        assert_equal(len(warnings), 2)
    def test_send_reminders_send_email_fails(self):
        """send_mail fails, we make sure the error is raised and should_send_reminders is
        disabled."""
        video = VideoFactory(
            live_state=IDLE,
            live_type=RAW,
            starting_at=timezone.now() + timedelta(days=2),
        )

        registration = LiveRegistrationFactory(
            anonymous_id=uuid.uuid4(),
            created_on=timezone.now() - timedelta(days=32),
            email="*****@*****.**",
            is_registered=True,
            should_send_reminders=True,
            video=video,
        )

        with mock.patch.object(
            send_reminders,
            "send_mail",
            side_effect=smtplib.SMTPException("Error SMTPException"),
        ):
            out = StringIO()
            err_out = StringIO()
            call_command("send_reminders", stdout=out, stderr=err_out)
            self.assertEqual(len(mail.outbox), 0)
            self.assertIn(
                f"Sending email for liveregistration {registration.id} for video "
                f"{registration.video.id} step {settings.REMINDER_3}",
                out.getvalue(),
            )
            self.assertIn("Mail failed [email protected]", err_out.getvalue())
            registration.refresh_from_db()
            # key has been added
            self.assertEqual(
                [settings.REMINDER_3, settings.REMINDER_ERROR], registration.reminders
            )
            out.close()

        # we call the command, no email should be sent
        call_command("send_reminders")
        self.assertEqual(len(mail.outbox), 0)
 def test_email_notification(self, mock_mail):
     skul = self.create_school()
     skul.settlement_school = 'edmc'
     noti = self.create_notification(skul)
     msg = noti.notify_school()
     self.assertTrue('failed' in msg)
     contact = self.create_contact()
     contact.endpoint = ''
     contact.save()
     skul.contact = contact
     skul.save()
     noti2 = self.create_notification(skul)
     msg1 = noti2.notify_school()
     self.assertTrue(mock_mail.call_count == 1)
     self.assertTrue('email' in msg1)
     noti3 = self.create_notification(skul)
     mock_mail.side_effect = smtplib.SMTPException('fail')
     msg = noti3.notify_school()
     self.assertTrue(mock_mail.call_count == 2)
 def starttls(self, keyfile=None, certfile=None):
     if not self.has_extn("starttls"):
         msg = b"STARTTLS extension not supported by server"
         raise smtplib.SMTPException(msg)
     (resp, reply) = self.docmd("STARTTLS")
     if resp == 220:
         self.sock = sslutil.wrapsocket(
             self.sock,
             keyfile,
             certfile,
             ui=self._ui,
             serverhostname=self._host,
         )
         self.file = self.sock.makefile("rb")
         self.helo_resp = None
         self.ehlo_resp = None
         self.esmtp_features = {}
         self.does_esmtp = 0
     return (resp, reply)