bgneal@180: from socket import error as socket_error bgneal@180: import smtplib bgneal@180: import time bgneal@316: import logging bgneal@180: bgneal@180: import django.core.mail bgneal@180: bgneal@180: import mailer.models bgneal@180: bgneal@180: bgneal@180: def enqueue_mail(subject, message, from_email, recipient_list): bgneal@180: """Creates mailer mail queue entries for the given email.""" bgneal@180: bgneal@180: if len(subject) > mailer.models.MAX_SUBJECT: bgneal@180: subject = u'%s...' % subject[:mailer.models.MAX_SUBJECT - 3] bgneal@180: bgneal@180: for recipient in recipient_list: bgneal@180: mailer.models.Message( bgneal@180: from_address=from_email, bgneal@180: to_address=recipient, bgneal@180: subject=subject, bgneal@180: body=message).save() bgneal@180: bgneal@180: bgneal@180: def send_queued_mail(): bgneal@180: """Reads the queued messages from the database, sends them, and removes them bgneal@180: from the queue.""" bgneal@180: bgneal@180: sent, errors = 0, 0 bgneal@180: bgneal@180: logging.debug("Sending queued mail...") bgneal@180: start_time = time.time() bgneal@180: bgneal@180: msgs = mailer.models.Message.objects.all() bgneal@180: for msg in msgs: bgneal@180: try: bgneal@180: django.core.mail.send_mail( bgneal@316: msg.subject, bgneal@316: msg.body, bgneal@316: msg.from_address, bgneal@180: [msg.to_address], bgneal@180: fail_silently=False) bgneal@180: except (socket_error, smtplib.SMTPException), e: bgneal@180: errors += 1 bgneal@316: logging.error("Error sending queued mail: %s", e) bgneal@180: else: bgneal@316: sent += 1 bgneal@316: msg.delete() bgneal@180: bgneal@180: end_time = time.time() bgneal@180: logging.debug("Sent queued mail: %d successful, %d error(s); elapsed time: %.2f" % ( bgneal@180: sent, errors, end_time - start_time))