Exemplo n.º 1
0
 def deliver(self, message):
     # TODO: Utilize -F full_name (sender full name), -f sender (envelope sender), -V envid (envelope ID), and space-separated BCC recipients
     # TODO: Record the output of STDOUT and STDERR to capture errors.
     proc = os.popen('%s -t -i' % (self.executable, ), 'w')
     proc.write(bytes(message))
     status = proc.close()
     
     if status != 0:
         raise MessageFailedException("Status code %d." % (status, ))
Exemplo n.º 2
0
 def deliver(self, message):
     result = self.connection.append(
             self.folder,
             '', # TODO: Set message urgency / flagged state.
             message.date.timetuple() if message.date else datetime.now(),
             bytes(message)
         )
     
     if result[0] != b'OK':
         raise MessageFailedException("\n".join(result[1]))
Exemplo n.º 3
0
    def test_message_failure(self):
        self.manager.startup()

        exc = MessageFailedException()

        self.assertRaises(DeliveryFailedException, self.manager.deliver, exc)

        self.assertEquals(self.states, ['running', 'stopped'])
        self.assertEquals(self.messages, [exc])

        self.manager.shutdown()
        self.assertEquals(self.states, ['running', 'stopped'])
Exemplo n.º 4
0
    def send_with_smtp(self, message):
        sender = bytes(message.envelope)
        recipients = message.recipients.string_addresses
        content = bytes(message)

        try:
            self.connection.sendmail(sender, recipients, content)
            self.sent += 1

        except SMTPSenderRefused as e:
            # The envelope sender was refused.  This is bad.
            log.error("%s REFUSED %s %s", message.id, e.__class__.__name__, e)
            raise MessageFailedException(str(e))

        except SMTPRecipientsRefused as e:
            # All recipients were refused. Log which recipients.
            # This allows you to automatically parse your logs for bad e-mail addresses.
            log.warning("%s REFUSED %s %s", message.id, e.__class__.__name__,
                        e)
            raise MessageFailedException(str(e))

        except SMTPServerDisconnected as e:  # pragma: no cover
            if message.retries >= 0:
                log.warning("%s DEFERRED %s", message.id,
                            "SMTPServerDisconnected")
                message.retries -= 1

            raise TransportFailedException()

        except Exception as e:  # pragma: no cover
            cls_name = e.__class__.__name__
            log.debug("%s EXCEPTION %s", message.id, cls_name, exc_info=True)

            if message.retries >= 0:
                log.warning("%s DEFERRED %s", message.id, cls_name)
                message.retries -= 1

            else:
                log.exception("%s REFUSED %s", message.id, cls_name)
                raise TransportFailedException()
Exemplo n.º 5
0
    def deliver(self, message):
        # TODO: Utilize -F full_name (sender full name), -f sender (envelope sender), -V envid (envelope ID), and space-separated BCC recipients
        # TODO: Record the output of STDOUT and STDERR to capture errors.
        # proc = Popen('%s -t -i' % (self.executable,), shell=True, stdin=PIPE)
        args = [self.executable, '-t', '-i']

        if message.sendmail_f:
            log.info("sendmail_f : {}".format(message.sendmail_f))
            args.extend(['-f', message.sendmail_f])

        proc = Popen(args, shell=False, stdin=PIPE)
        proc.communicate(bytes(message))
        proc.stdin.close()
        if proc.wait() != 0:
            raise MessageFailedException("Status code %d." %
                                         (proc.returncode, ))
Exemplo n.º 6
0
    def _batchsend(self):
        request = urllib2.Request(
            "https://api.postmarkapp.com/email/batch",
            json.dumps(self.messages),
            {
                'Accept': "application/json",
                'Content-Type': "application/json",
                'X-Postmark-Server-Token': self.key,
            }
        )

        try:
            response = urllib2.urlopen(request)
        except (urllib2.HTTPError, urllib2.URLError) as e:
            raise DeliveryFailedException(e, "Could not connect to Postmark.")
        else:
            respcode = response.getcode()
            if respcode >= 400 and respcode <= 499:
                raise MessageFailedException(response.read())
            elif respcode >= 500 and respcode <= 599:
                raise DeliveryFailedException(self.messages[0], "Postmark service unavailable. Just diplaying first message of batch")

        del self.messages[:]
Exemplo n.º 7
0
    def deliver(self, message):

        to = message.to

        # Sendgrid doesn't accept CC over the api
        if message.cc:
            to.extend(message.cc)

        args = dict({
            'from': [
                fromaddr.address.encode(message.encoding)
                for fromaddr in message.author
            ],
            'fromname': [
                fromaddr.name.encode(message.encoding)
                for fromaddr in message.author
            ],
            'to': [toaddr.address.encode(message.encoding) for toaddr in to],
            'toname': [toaddr.name.encode(message.encoding) for toaddr in to],
            'subject':
            message.subject.encode(message.encoding),
            'text':
            message.plain.encode(message.encoding)
        })

        if message.bcc:
            args['bcc'] = [
                bcc.address.encode(message.encoding) for bcc in message.bcc
            ]

        if message.reply:
            args['replyto'] = message.reply.encode(message.encoding)

        if message.rich:
            args['html'] = message.rich.encode(message.encoding)

        if message.attachments:
            # Not implemented yet
            """
            attachments = []
            
            for attachment in message.attachments:
                attachments.append((
                        attachment['Content-Disposition'].partition(';')[2],
                        attachment.get_payload(True)
                    ))
            
            msg.attachments = attachments
            """
            raise MailConfigurationException()

        if not self.bearer:
            args['api_user'] = self.user
            args['api_key'] = self.key

        request = urllib2.Request("https://sendgrid.com/api/mail.send.json",
                                  urllib.urlencode(args, True))

        if self.bearer:
            request.add_header("Authorization", "Bearer %s" % self.key)

        try:
            response = urllib2.urlopen(request)
        except (urllib2.HTTPError, urllib2.URLError):
            raise DeliveryFailedException(message,
                                          "Could not connect to Sendgrid.")
        else:
            respcode = response.getcode()

            if respcode >= 400 and respcode <= 499:
                raise MessageFailedException(response.read())
            elif respcode >= 500 and respcode <= 599:
                raise DeliveryFailedException(message,
                                              "Sendgrid service unavailable.")

            response.close()
Exemplo n.º 8
0
        request = urllib2.Request(
            "https://api.postmarkapp.com/email/batch",
            json.dumps(self.messages), {
                'Accept': "application/json",
                'Content-Type': "application/json",
                'X-Postmark-Server-Token': self.key,
            })

        try:
            response = urllib2.urlopen(request)
        except (urllib2.HTTPError, urllib2.URLError), e:
            raise DeliveryFailedException(e, "Could not connect to Postmark.")
        else:
            respcode = response.getcode()
            if respcode >= 400 and respcode <= 499:
                raise MessageFailedException(response.read())
            elif respcode >= 500 and respcode <= 599:
                raise DeliveryFailedException(
                    self.messages[0],
                    "Postmark service unavailable. Just diplaying first message of batch"
                )

        del self.messages[:]

    def startup(self):
        self.messages = []

    def deliver(self, message):
        if len(self.messages) >= 500:
            # Postmark allows to send a maximum of 500 emails over its batch API
            self._batchsend()