#!/usr/bin/python3
import base64
+import datetime
import email
import email.mime.multipart
import email.mime.text
def bounce_email_address(self):
return self.settings.get("bounce_email_address")
- def _send(self, message, sender=None, priority=0):
- res = self.db.get("INSERT INTO messages(message, priority) \
- VALUES(%s, %s) RETURNING id", message, priority)
-
- logging.debug("Message queued with ID %s" % res.id)
-
- def send(self, message, priority=0, headers={}):
+ def send(self, message, priority=0, headers={}, after=None):
# Convert message from string
if not isinstance(message, email.message.Message):
message = email.message_from_string(message)
+ # Send messages immediately by default
+ if after is None:
+ after = datetime.datetime.now()
+
+ # If after is relative, we make it absolute
+ elif isinstance(after, datetime.timedelta):
+ after = datetime.datetime.now() + after
+
# Add a message ID if non exsist
if not "Message-Id" in message and not "Message-ID" in message:
message.add_header("Message-Id", self.make_msgid())
except KeyError:
message.add_header(k, v)
- # Add date if the message doesn't have one already
- if "Date" not in message:
- message.add_header("Date", email.utils.formatdate())
-
# Send any errors to the bounce address
if self.bounce_email_address:
message.add_header("Errors-To", "<%s>" % self.bounce_email_address)
- # Send the message
- self._send(message.as_string(), priority=priority)
+ # Add the message to the queue
+ res = self.db.get("""
+ INSERT INTO
+ messages
+ (
+ message,
+ priority,
+ send_after
+ )
+ VALUES
+ (
+ %s, %s, %s
+ )
+ RETURNING
+ id
+ """, message.as_string(), priority, after,
+ )
+
+ logging.debug("Message queued with ID %s" % res.id)
def send_template(self, template_name,
- sender=None, priority=0, headers={}, **kwargs):
+ sender=None, priority=0, headers={}, after=None, **kwargs):
"""
Send a message based on the given template
"""
message.attach(message_part)
# Send the message
- self.send(message, priority=priority, headers=headers)
+ self.send(message, priority=priority, headers=headers, after=after)
# In debug mode, re-compile the templates with every request
if self.backend.debug:
class Queue(misc.Object):
@property
def messages(self):
- return self.db.query("SELECT * FROM messages \
- WHERE time_sent IS NULL \
- ORDER BY priority DESC, time_created ASC")
+ return self.db.query("""
+ SELECT
+ *
+ FROM
+ messages
+ WHERE
+ time_sent IS NULL
+ AND
+ send_after >= CURRENT_TIMESTAMP
+ ORDER BY
+ priority DESC,
+ time_created ASC
+ """)
@lazy_property
def relay(self):