0

I'd like to be able to change sender email address from the admin. However, the default sender email is specified in settings.py with DEFAULT_FROM_EMAIL.

What's a good approach to achieving this?

Edit:
The main problem here is that DEFAULT_FROM_EMAIL is used by third-party apps included in my project, and I'd like to avoid messing with their code, for obvious reasons...

frnhr
  • 12,354
  • 9
  • 63
  • 90

2 Answers2

0

Don't use settings.py for dynamic settings. There is a great application for this:

François Constant
  • 5,531
  • 1
  • 33
  • 39
  • Nice app, but I don't think it overrides values in settings.py. I'd love to use it, but the thing is that DEFAULT_FROM_EMAIL is used by other apps, e.g. contrib.auth and some others, so my options are limited. – frnhr Jul 04 '15 at 11:46
  • No it doesn't overrides values in `settings.py`. I don't think you can update these settings at runtime (if you test it, keep in mind to use production settings). I understand that you don't want to mess with other apps but changing the auth emails isn't that hard and you might want to personalise them at some point anyway... – François Constant Jul 06 '15 at 23:29
0

Haven't tested this yet, but I think it might be a way to go about this particular problem.This seems to do the trick rather nicely. Comments welcome!

from UserString import UserString

def get_dynamic_sender():
    return "Sender A"  # expand here...

class DynamicEmailValue(UserString):
    _data = None
    @property
    def data(self):
        return self._data.format(name=get_dynamic_sender())
    @data.setter
    def data(self, value):
        self._data = value

Instances of this class behave just like regular strings:

>>> DEFAULT_FROM_EMAIL = DynamicEmailValue('{name} <some.mail@example.com>')

>>> DEFAULT_FROM_EMAIL
'Sender A <some.mail@example.com>'

>>> "sent by " + DEFAULT_FROM_EMAIL + " two days ago"
'sent by Sender A <some.mail@example.com> two days ago'

>>> "from: {}".format(DEFAULT_FROM_EMAIL)
'from: Sender A <some.mail@example.com>'

>>> "from: %s" % DEFAULT_FROM_EMAIL
'from: Sender A <some.mail@example.com>'

>>> dynamic_sender = "Sender B"

>>> "from: %s" % DEFAULT_FROM_EMAIL
'from: Sender B <some.mail@example.com>'

Note:

  • Works only in Python 2.x
  • Not 100% tested with Django (settings might be cached at some places, etc.)
  • Assigning a new value to it after initialization (DEFAULT_FROM_EMAIL = 'new value') renders the whole thing mute, unless the new value also contains {name}. But settings should not get written to, so this probably won't happen... hopefully... yeah...
frnhr
  • 12,354
  • 9
  • 63
  • 90