Code Monkey home page Code Monkey logo

django-post_office's People

Contributors

adamchainz avatar bashu avatar christophmeissner avatar clickonchris avatar domdinicola avatar edenilsonferreira00 avatar embedded1 avatar fendyh avatar fizista avatar franciscobmacedo avatar hockeybuggy avatar ivlevdenis avatar jessicarasidi avatar jhoos avatar jrief avatar kakulukia avatar marsha97 avatar mogost avatar pacahon avatar petrprikryl avatar rpkilby avatar seiryuz avatar selwin avatar stefan-mihaila avatar timgates42 avatar wadevries avatar yprez avatar zagl avatar zshihang avatar zwack avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-post_office's Issues

Having issues automating mail send through celery - KeyError: 'lockfile'

Hi there,

I'm trying to periodically send out queued up mail with celery. The way I'm going about this is by creating a task that I will periodically call, which basically just calls into the function that triggers mail send. This function looks like this:

from post_office import mail
from post_office.management.commands import send_queued_mail

@task
def send_emails():
    cmd = send_queued_mail.Command()
    cmd.execute(processes=1)

When this task gets called, I see the following stack trace within RabbitMQ:

[2014-10-12 22:15:43,877: ERROR/MainProcess] Task booker.tasks.send_emails[26d93b2e-20ed-448f-ae19-29615a2a7906] raised unexpected: KeyError('lockfile',)
Traceback (most recent call last):
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/celery/app/trace.py", line 437, in __protected_call__
    return self.run(*args, **kwargs)
  File "/Users/chris/dev/bitbucket/myapp/myapp/booker/tasks.py", line 11, in send_emails
    cmd.execute(processes=num_processes)
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/post_office/management/commands/send_queued_mail.py", line 29, in handle
    options['lockfile'])
KeyError: 'lockfile'
[2014-10-12 22:15:43,887: ERROR/MainProcess] Task booker.tasks.send_emails[b61c6620-cd4c-472b-9ebb-e8cf7ef782e7] raised unexpected: KeyError('lockfile',)
Traceback (most recent call last):
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/celery/app/trace.py", line 437, in __protected_call__
    return self.run(*args, **kwargs)
  File "/Users/chris/dev/bitbucket/myapp/myapp/booker/tasks.py", line 11, in send_emails
    cmd.execute(processes=num_processes)
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/post_office/management/commands/send_queued_mail.py", line 29, in handle
    options['lockfile'])
KeyError: 'lockfile'
[2014-10-12 22:15:43,888: ERROR/MainProcess] Task booker.tasks.send_emails[63c97beb-d56c-44ec-ac0a-07d1b0b77a69] raised unexpected: KeyError('lockfile',)
Traceback (most recent call last):
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/celery/app/trace.py", line 437, in __protected_call__
    return self.run(*args, **kwargs)
  File "/Users/chris/dev/bitbucket/myapp/myapp/booker/tasks.py", line 11, in send_emails
    cmd.execute(processes=num_processes)
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "/Users/chris/Envs/myappvenv/lib/python2.7/site-packages/post_office/management/commands/send_queued_mail.py", line 29, in handle
    options['lockfile'])
KeyError: 'lockfile'

I'm not seeing any clear documentation on the expected usage of this with Celery, so I may be misusing it entirely... Is this a misuse of the library entirely, or is there a deeper issue at play? How do I trigger periodically emptying the queue and sending out pending emails?

Allow content to be rendered during delivery

For emails that are rendered from templates, we can avoid storing the rendered content/HTML content by rendering them from the template just before delivery. Depending on usage, this may result in significant space savings.

Suggestion: send mode with "fire and forget"

Hi there,

In some cases (e.g. sending an URL for resetting a password), you may not want a successfully-sent mail to remain in the database.
I would suggest the addition of a "fire and forget" send mode that would delete the email if it is sent successfully.

regards
LAI

Migration 0011 error

Hitting this migration error today, anyone else experience this?

Running migrations for post_office:
 - Migrating forwards to 0011_auto__chg_field_email_context.
 > post_office:0011_auto__chg_field_email_context
FATAL ERROR - The following SQL query failed: ALTER TABLE "post_office_email" ALTER COLUMN "context" TYPE json, ALTER COLUMN "context" DROP NOT NULL, ALTER COLUMN "context" DROP DEFAULT;
The error was: column "context" cannot be cast automatically to type json
HINT:  Specify a USING expression to perform the conversion.

Is there an option to send plain text emails?

Hi, thanks for the great project!

Currently to send plain text emails I just don't set the html_content field in the email template.

Is there a way to do this conditionally? Such as a setting to send plain text even if the email template has html_content set?

Thanks

postgresql-9.1-main.log => UTC LOG: unexpected EOF on client connection

This message is filling up my postgres log when I'm using the management commands. The problems occur because connections are not closed properly. I fixed it this way:

===== cleanup_mail.py & send_queued_mail.py =====
==> from django import db
from django.core.management.base import BaseCommand

===== cleanup_mail.py =====
Email.objects.only('id').filter(created__lt=cutoff_date).delete()
==> db.close_connection()

===== send_queued_mail.py =====
send_queued(options['processes'], options['log_level'])
==> db.close_connection()

More direct replacement: add configuration option to always send email immediately

I don't have a large volume of email, and am more using django-post_office for the templating functionality.

If there were a settings configuration option for email to just send immediately (including from all other third-party apps, so setting priority isn't an option), rather than being queued, then it would be a direct replacement for the original send_mail and not require setting up cron or the similar just to send email.

(I'll have a look at doing this myself when I get a moment, so this is more just noting the feature request, not expecting an implementation.)

Choose Content Disposition

Is it possible to add an image as inline attachment.

How it works now when using create_attachements:
Content-Disposition: attachment; filename="logo.png"

How I'd like to attach image:
Content-ID: <BV1AYY> Content-Disposition: inline; filename="logo.png"

Migrations failing on upgrade from Python 2.7 to Python 3.4/Django 1.5 to Django 1.7

I'm upgrading a web app I built for my company from Python 2.7 to Python 3.4 and Django 1.5 to Django 1.7. I followed the 1.7 release note instructions for porting from South to native Django migrations and most things seemed to work fine. My test suite returned some errors on things using emails. Visiting the post_office Email change page in the Django admin resulted in this error message with post_office 1.0.0. I tried using the latest post_office from Git and it also failed:

Django Version: 1.7
Python Version: 3.4.1
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'braces',
 'ckeditor',
 'crispy_forms',
 'django_bleach',
 'django_comments',
 'haystack',
 'post_office',
 'register',
 'registration',
 'taggit',
 'community',
 'complaints',
 'decisions',
 'events',
 'guidance',
 'kpis',
 'news',
 'programme',
 'quanda',
 'SARs',
 'schemes',
 'travel',
 'debug_toolbar')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware')


Traceback:
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/contrib/admin/options.py" in wrapper
  567.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/contrib/admin/sites.py" in inner
  204.             return view(request, *args, **kwargs)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapper
  29.             return bound_func(*args, **kwargs)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/utils/decorators.py" in bound_func
  25.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/contrib/admin/options.py" in changelist_view
  1576.             selection_note=_('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/models/query.py" in __len__
  122.         self._fetch_all()
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/models/query.py" in _fetch_all
  966.             self._result_cache = list(self.iterator())
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/models/query.py" in iterator
  265.         for row in compiler.results_iter():
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in results_iter
  700.         for rows in self.execute_sql(MULTI):
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in execute_sql
  786.             cursor.execute(sql, params)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/debug_toolbar/panels/sql/tracking.py" in execute
  174.         return self._record(self.cursor.execute, sql, params)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/debug_toolbar/panels/sql/tracking.py" in _record
  104.             return method(sql, params)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
  81.             return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/utils/six.py" in reraise
  549.             raise value.with_traceback(tb)
File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /sN0won2june/post_office/email/
Exception Value: column post_office_email.cc does not exist
LINE 1: ...ce_email"."from_email", "post_office_email"."to", "post_offi...

I think the problem might lie in the migrations. These seemed to work with 1.0.0 but, using the Git master, I got this error:

Applying post_office.0001_initial...Traceback (most recent call last):
  File "manage.py", line 11, in <module>
    execute_from_command_line(sys.argv)
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 160, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/migrations/executor.py", line 63, in migrate
    self.apply_migration(migration, fake=fake)
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/migrations/executor.py", line 91, in apply_migration
    if self.detect_soft_applied(migration):
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/migrations/executor.py", line 135, in detect_soft_applied
    apps = project_state.render()
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/migrations/state.py", line 67, in render
    model.render(self.apps)
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/migrations/state.py", line 311, in render
    body,
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/models/base.py", line 171, in __new__
    new_class.add_to_class(obj_name, obj)
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/models/base.py", line 300, in add_to_class
    value.contribute_to_class(cls, name)
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/models/fields/related.py", line 1572, in contribute_to_class
    super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only)
  File "/home/gary/intranet_upgrade/lib/python3.4/site-packages/django/db/models/fields/related.py", line 264, in contribute_to_class
    'app_label': cls._meta.app_label.lower()
TypeError: unsupported operand type(s) for %: 'bytes' and 'dict'

Normally I'd post something like this on Stack Overflow but this one looked like it might be a bug so I'm posting here. Let me know if I'm wrong and I'll move to SO. Sorry not to suggest a fix but this one looks beyond me.

Simplify integration with task queues by adding default priority setting

I want to use Celery to dispatch my emails asynchronously and find setting priority=PRIORITY.now on each send() a bit too verbose and error prone (emails won't get sent if forgotten!).

But if I understand things correctly, that's what should be done when using a backend that uses workers to send the emails.

Hence, I suggest (and am willing to send a PR) to introduce another setting which allows specifying the default priority. Just wanted to check if I might miss something and if it's agreed on before I get to work on the PR.

Filesystem-based Templates?

Hi, thanks for the great work!

What's the reason behind database-backed email templates? Is there a way to store templates from the filesystem instead? For example, I want email templates under revision control.

Daniel

Post office spams my database with error logs

I installed post-office and it works fine except that it put tons of error messages about broken links in its
email database. It is fine for me to fix the errors, but I feel my database is not the right place for that kind of error log, but I do not know how to stop that. How shoud I set my settings? What might be causing this?

Python3 error with django-jsonfield

Steps to reproduce:

  1. install django-post_office into a python3.3 virtualenv
  2. create a template and send 1 email
  3. Try to view that email at /admin/post_office/email/1/

Results: NameError: global name 'basestring' is not defined

This occurs in django-jsonfield (widgets.py, line 12).

So it seems that django-jsonfield is not Python3 compatible. Interestingly there is a separate project 'jsonfield' which is Python3 compatible and django-post_office seems to work well with it.

Attachment support?

Hi,
Is there support for sending email attachments in post_office?
I couldn't find any mention in the code or the docs...

Emails are being sent latest first and I need vice versa

I'm using the default priority which is Medium and a cron job to pick the emails out
of the queue for sending but emails are being sent lastest first due to "order_by(-priority)"

How can I achieve my goal which is sending out the oldest email in queue first?

thanks for this wonderful library

Error django 1.7 - RemovedInDjango18Warning

Hi
I got this error when i running my project with django 1.7

.virtualenvs/ownproject/lib/python2.7/site-packages/django/forms/widgets.py:143: RemovedInDjango18Warning: EmailAdmin.queryset method should be renamed get_queryset.
.new(mcs, name, bases, attrs))

any clue how to fix?

Recipients emails should support display name

Hi there,

I'm getting a ValidationError when sending mails with display names, e.g. John Smith [email protected]

Want to fix it?

Put the following lines in utils:

import re
from django.core.validators import EmailValidator

class FullEmailValidator(EmailValidator):
    """ Simple validator that passes for email addresses bearing a display name
    i.e. John Smith <[email protected]>
    """
    def __call__(self, value):
        try:
            res = super(FullEmailValidator, self).__call__(value)
        except ValidationError:
            try:
                split_address = re.match(r'(.+) \<(.+@.+)\>', value)
                display_name, email = split_address.groups()
                super(FullEmailValidator, self).__call__(email)
            except AttributeError:
                raise ValidationError

validate_email = FullEmailValidator()

Also, in utils replace in validate_comma_separated_emails() the call to validate_email by validate_email_with_name:

def validate_comma_separated_emails(value):
"""
Validate every email address in a comma separated list of emails.
"""
    if not isinstance(value, (tuple, list)):
        raise ValidationError('Email list must be a list/tuple.')

    for email in value:
        try:
            validate_email_with_name(email)
        except ValidationError:
            raise ValidationError('Invalid email: %s' % email, code='invalid')

cheers

Test fails due to invalid email DEFAULT_FROM_EMAIL address

ERROR: test_default_sender (post_office.tests.models.ModelTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./post_office/tests/models.py", line 137, in test_default_sender
    emails = send(['[email protected]'], subject='foo')
  File "./post_office/mail.py", line 60, in send
    priority=priority)
  File "./post_office/utils.py", line 30, in send_mail
    priority=priority
  File "/Users/wouter/dev/envs/postoffice/lib/python2.6/site-packages/django/db/models/manager.py", line 149, in create
    return self.get_query_set().create(**kwargs)
  File "/Users/wouter/dev/envs/postoffice/lib/python2.6/site-packages/django/db/models/query.py", line 402, in create
    obj.save(force_insert=True, using=self.db)
  File "./post_office/models.py", line 108, in save
    self.full_clean()
  File "/Users/wouter/dev/envs/postoffice/lib/python2.6/site-packages/django/db/models/base.py", line 926, in full_clean
    raise ValidationError(errors)
ValidationError: {'from_email': [u'Enter a valid e-mail address.']}

----------------------------------------------------------------------

This is because it uses the DEFAULT_FROM_EMAIL from global_settings (Django 1.5.1), which is 'webmaster@localhost', which does not pass the validators.validate_email_with_name's regex, which requires the address to end with a tld.

Simple fix; set DEFAULT_FROM_EMAIL in test_settings to '[email protected]'.
Or; relax the validator's regex.

Sending Queued mail failed, Django

[INFO]10-06-2014 12:00:02 PID 14886: Process started, sending 160 emails
Traceback (most recent call last):
File "/home/byld/placement/placement/manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(_args, *_options.dict)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 285, in execute
output = self.handle(_args, *_options)
File "/usr/local/lib/python2.7/dist-packages/post_office/management/commands/send_queued_mail.py", line 23, in handle
with FileLock(tempfile.gettempdir() + "/post_office", timeout=1):
File "/usr/local/lib/python2.7/dist-packages/post_office/lockfile.py", line 111, in enter
if not self.is_locked():
File "/usr/local/lib/python2.7/dist-packages/post_office/lockfile.py", line 96, in is_locked
raise FileLocked()
post_office.lockfile.FileLocked
Traceback (most recent call last):
File "/home/byld/placement/placement/manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 399, in execute_from_command_line
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(_args, *_options.dict)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 285, in execute
output = self.handle(_args, *_options)
File "/usr/local/lib/python2.7/dist-packages/post_office/management/commands/send_queued_mail.py", line 23, in handle
with FileLock(tempfile.gettempdir() + "/post_office", timeout=1):
File "/usr/local/lib/python2.7/dist-packages/post_office/lockfile.py", line 111, in enter
if not self.is_locked():
File "/usr/local/lib/python2.7/dist-packages/post_office/lockfile.py", line 96, in is_locked
raise FileLocked()
post_office.lockfile.FileLocked
Traceback (most recent call last):
File "/home/byld/placement/placement/manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(_args, *_options.dict)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 285, in execute
output = self.handle(_args, *_options)
File "/usr/local/lib/python2.7/dist-packages/post_office/management/commands/send_queued_mail.py", line 23, in handle
with FileLock(tempfile.gettempdir() + "/post_office", timeout=1):
File "/usr/local/lib/python2.7/dist-packages/post_office/lockfile.py", line 111, in enter
if not self.is_locked():
File "/usr/local/lib/python2.7/dist-packages/post_office/lockfile.py", line 96, in is_locked
raise FileLocked()
post_office.lockfile.FileLocked
Traceback (most recent call last):
File "/home/byld/placement/placement/manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(_args, *_options.dict)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 285, in execute
output = self.handle(_args, *_options)
File "/usr/local/lib/python2.7/dist-packages/post_office/management/commands/send_queued_mail.py", line 23, in handle
with FileLock(tempfile.gettempdir() + "/post_office", timeout=1):
File "/usr/local/lib/python2.7/dist-packages/post_office/lockfile.py", line 111, in enter
if not self.is_locked():
File "/usr/local/lib/python2.7/dist-packages/post_office/lockfile.py", line 96, in is_locked
raise FileLocked()
post_office.lockfile.FileLocked
Traceback (most recent call last):
File "/home/byld/placement/placement/manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(_args, *_options.dict)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 285, in execute
output = self.handle(_args, *_options)
File "/usr/local/lib/python2.7/dist-packages/post_office/management/commands/send_queued_mail.py", line 23, in handle
with FileLock(tempfile.gettempdir() + "/post_office", timeout=1):
File "/usr/local/lib/python2.7/dist-packages/post_office/lockfile.py", line 111, in enter
if not self.is_locked():
File "/usr/local/lib/python2.7/dist-packages/post_office/lockfile.py", line 96, in is_locked
raise FileLocked()
post_office.lockfile.FileLocked
[INFO]10-06-2014 12:03:40 PID 14886: Process finished, 160 emails attempted, 79 sent, 81 failed
[INFO]10-06-2014 12:03:40 PID 14886: 160 emails attempted, 79 sent, 81 failed

Priority must be an integer

Following the instructions in the readme:

>>> mail.send(
...     ['[email protected]'],
...     '[email protected]',
...     template='welcome_email',
...     context={'foo': 'bar'},
...     priority='now',
... )
Traceback (most recent call last):
  File "<input>", line 6, in <module>
  File "...../post_office/mail.py", line 68, in send
    for recipient in recipients]
  File "...../post_office/mail.py", line 45, in from_template
    headers=headers, priority=priority, status=status
  File "...../django/db/models/manager.py", line 149, in create
    return self.get_query_set().create(**kwargs)
  File "...../django/db/models/query.py", line 416, in create
    obj.save(force_insert=True, using=self.db)
  File "...../post_office/models.py", line 119, in save
    self.full_clean()
  File "...../django/db/models/base.py", line 926, in full_clean
    raise ValidationError(errors)
ValidationError: {'priority': [u"'now' value must be an integer."]}

The solution is to use PRIORITY.now instead of the string value.

Docs update needed? Or maybe send() should accept a string representation of "priority"?

django admin popups for EmailTemplate ForeignKeys fails

 File ".env/local/lib/python2.7/site-packages/django/utils/html.py", line 65, in escapejs
   return mark_safe(force_text(value).translate(_js_escapes))
  TypeError: expected a character buffer object

this is easily fixed by replasing str with unicode in models.EmailTemplate.__unicode__

Context fields visible in django admin edit page.

We can user template context variable in mail content, thats very good.
Can we some how display the context variables available for a given template in the edit page. This will help editor to use them without looking at the code that sends the mail.

I had a similar implementation where i added a field (context_variables) which displays the template variables available.
Problem with my application was that, editor may delete the values from there.
Some how we should set the permissions that if the editor is super_user, he can edit the field context_variables, for others this will be non-editable field.

FileLockException: Timeout occured.

Hi,

Every time I try to send mails I get "FileLockException: Timeout occured.". It worked great for months and now It doesn't. Reboot doesn't help. Any ideas?

Bests,
Philip

Drop some indexes

Low cardinality indexes and infrequently used indexes:

  • Log.status
  • Email.priority

Unused indexes:

  • Log.date

Allow default priority to be customized

Currently, all mail sending will have default priority of PRIORITY.medium,

Would it be acceptable if we introduce new setting, like POST_OFFICE_DEFAULT_PRIORITY?

In some use case(my small project for example), we need to send email mostly with PRIORITY.now, only in some cases that we use PRIORITY.medium. Calling mail.send has become cumbersome due to writing PRIORITY.now everywhere.

Running send_queued_mail every 60s on Heroku - opens a new db connection every time - maxing out my connections

Does send_queued_mail close it's db connection when done? Doesn't seem to be. Perhaps it is how I am calling it via a scheduler so it runs every 60s. That file below as an fyi


import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'anonqaproject.settings'
import logging
logging.basicConfig()
from apscheduler.scheduler import Scheduler
from post_office import utils
sched = Scheduler()

@sched.interval_schedule(minutes=1)
def timed_job():
utils.send_queued_mail()

sched.start()
while True:

pass

Celery integration

I wonder if you have some recommendation to integrate it with Celery ?

Signature of post_office.utils.send_mail does not match django.core.mail.send_mail

Post Office's send_mail function unfortunately does not accept the same arguments as Django's own counterpart. This breaks things when trying to use Post Office to send mails when an app tries to use arguments which Django does accept, such as fail_silently. This is particularly an issue when using the Postman package, which has a setting on which send_mail function to use and could thus be configured to use Post Office's one (see https://bitbucket.org/psam/django-postman/src/b307189ff3f7e68b6c485175936eb790a59830b7/postman/utils.py?at=default#cl-23 for this feature). Because Postman innocently tries to use fail_silently when sending a mail, Python will whine about the arguments.

An easy but functioning workaround which we use is to use a very simple wrapper function which has a **kwargs in the signature to catch any arguments Post Office does not care about. For example:

def send_mail(subject, message, from_email, recipient_list, html_message='',
              scheduled_time=None, headers=None, priority=mail.PRIORITY.medium,
              **kwargs):
    # A wrapper for post_office.send_mail, because that doesn't have a **kwargs
    # in the signature, and Postman fails on it because of that.
    return post_office_send_mail(
        subject, message, from_email, recipient_list,
        html_message=html_message, scheduled_time=scheduled_time,
        headers=headers, priority=priority)

But I think this is a bug in Post Office. A tiny one, but still. Using **kwargs as well in Post Office is a simple but workable fix, but I don't know if that is proper in the context of Post Office.

502 bad gateway

Sometimes I get 502 error.

What I see in logs:
File "/usr/lib/python2.6/logging/init.py", line 679, in handle
self.emit(record)
File "/django/utils/log.py", line 113, in emit
mail.mail_admins(subject, message, fail_silently=True, html_message=html_message)
File "/django/core/mail/init.py", line 98, in mail_admins
mail.send(fail_silently=fail_silently)
File "/django/core/mail/message.py", line 255, in send
return self.get_connection(fail_silently).send_messages([self])
File "/post_office/backends.py", line 43, in send_messages
headers=headers, priority=PRIORITY.medium)
File "/django/db/models/manager.py", line 149, in create
return self.get_query_set().create(**kwargs)
File "/django/db/models/query.py", line 416, in create
obj.save(force_insert=True, using=self.db)
File "/post_office/models.py", line 119, in save
self.full_clean()
File "/django/db/models/base.py", line 926, in full_clean
raise ValidationError(errors)
django.core.exceptions.ValidationError: {'from_email': [u'Enter a valid e-mail address.']}

I have regular settings.DEFAULT_FROM_EMAIL
and EMAIL_BACKEND = 'post_office.EmailBackend'

django 1.5

Allow sending to more than one recipient

If I want to send an email to more then one recipient and just put to addresses into the recipients list I got two separate emails and not one with two recipients. How can I fix this?

admin shows inconsistent behavior

Hi,

the admin integration of post_office seems inconsistent and does not work (at least, not reliably).

  • Usually, post_office does not appear at all in the admin interface
  • Sometimes, post_office shows up, but then not all tables of my own app appear

I've not been able to reliably ascertain when which case happens; it looks a bit as if the order in INSTALLED_APPs matters, but not reliable either. Database newly created each time.

  • Django: 1.6.4
  • Post office django-post-office (0.8.4)
  • json_field: jsonfield (0.9.20)
  • python 2.7.2

Any ideas where to start looking?

thanks a lot,

Holger

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.