Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DESCRIPTION.rst 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. ==================
  2. Django Post Office
  3. ==================
  4. Django Post Office is a simple app to send and manage your emails in Django.
  5. Some awesome features are:
  6. * Allows you to send email asynchronously
  7. * Multi backend support
  8. * Supports HTML email
  9. * Supports database based email templates
  10. * Built in scheduling support
  11. * Works well with task queues like `RQ <http://python-rq.org>`_ or `Celery <http://www.celeryproject.org>`_
  12. * Uses multiprocessing (and threading) to send a large number of emails in parallel
  13. * Supports multilingual email templates (i18n)
  14. Dependencies
  15. ============
  16. * `django >= 1.8 <http://djangoproject.com/>`_
  17. * `django-jsonfield <https://github.com/bradjasper/django-jsonfield>`_
  18. Installation
  19. ============
  20. |Build Status|
  21. * Install from PyPI (or you `manually download from PyPI <http://pypi.python.org/pypi/django-post_office>`_)::
  22. pip install django-post_office
  23. * Add ``post_office`` to your INSTALLED_APPS in django's ``settings.py``:
  24. .. code-block:: python
  25. INSTALLED_APPS = (
  26. # other apps
  27. "post_office",
  28. )
  29. * Run ``migrate``::
  30. python manage.py migrate
  31. * Set ``post_office.EmailBackend`` as your ``EMAIL_BACKEND`` in django's ``settings.py``:
  32. .. code-block:: python
  33. EMAIL_BACKEND = 'post_office.EmailBackend'
  34. Quickstart
  35. ==========
  36. Send a simple email is really easy:
  37. .. code-block:: python
  38. from post_office import mail
  39. mail.send(
  40. 'recipient@example.com', # List of email addresses also accepted
  41. 'from@example.com',
  42. subject='My email',
  43. message='Hi there!',
  44. html_message='Hi <strong>there</strong>!',
  45. )
  46. If you want to use templates, ensure that Django's admin interface is enabled. Create an
  47. ``EmailTemplate`` instance via ``admin`` and do the following:
  48. .. code-block:: python
  49. from post_office import mail
  50. mail.send(
  51. 'recipient@example.com', # List of email addresses also accepted
  52. 'from@example.com',
  53. template='welcome_email', # Could be an EmailTemplate instance or name
  54. context={'foo': 'bar'},
  55. )
  56. The above command will put your email on the queue so you can use the
  57. command in your webapp without slowing down the request/response cycle too much.
  58. To actually send them out, run ``python manage.py send_queued_mail``.
  59. You can schedule this management command to run regularly via cron::
  60. * * * * * (/usr/bin/python manage.py send_queued_mail >> send_mail.log 2>&1)
  61. or, if you use uWSGI_ as application server, add this short snipped to the
  62. project's ``wsgi.py`` file:
  63. .. code-block:: python
  64. from django.core.wsgi import get_wsgi_application
  65. application = get_wsgi_application()
  66. # add this block of code
  67. try:
  68. import uwsgidecorators
  69. from django.core.management import call_command
  70. @uwsgidecorators.timer(10)
  71. def send_queued_mail(num):
  72. """Send queued mail every 10 seconds"""
  73. call_command('send_queued_mail', processes=1)
  74. except ImportError:
  75. print("uwsgidecorators not found. Cron and timers are disabled")
  76. Alternatively you can also use the decorator ``@uwsgidecorators.cron(minute, hour, day, month, weekday)``.
  77. This will schedule a task at specific times. Use ``-1`` to signal any time, it corresponds to the ``*``
  78. in cron.
  79. Please note that ``uwsgidecorators`` are available only, if the application has been started
  80. with **uWSGI**. However, Django's internal ``./manange.py runserver`` also access this file,
  81. therefore wrap the block into an exception handler as shown above.
  82. This configuration is very useful in environments, such as Docker containers, where you
  83. don't have a running cron-daemon.
  84. Usage
  85. =====
  86. mail.send()
  87. -----------
  88. ``mail.send`` is the most important function in this library, it takes these
  89. arguments:
  90. +--------------------+----------+--------------------------------------------------+
  91. | Argument | Required | Description |
  92. +--------------------+----------+--------------------------------------------------+
  93. | recipients | Yes | list of recipient email addresses |
  94. +--------------------+----------+--------------------------------------------------+
  95. | sender | No | Defaults to ``settings.DEFAULT_FROM_EMAIL``, |
  96. | | | display name is allowed (``John <john@a.com>``) |
  97. +--------------------+----------+--------------------------------------------------+
  98. | subject | No | Email subject (if ``template`` is not specified) |
  99. +--------------------+----------+--------------------------------------------------+
  100. | message | No | Email content (if ``template`` is not specified) |
  101. +--------------------+----------+--------------------------------------------------+
  102. | html_message | No | HTML content (if ``template`` is not specified) |
  103. +--------------------+----------+--------------------------------------------------+
  104. | template | No | ``EmailTemplate`` instance or name |
  105. +--------------------+----------+--------------------------------------------------+
  106. | language | No | Language in which you want to send the email in |
  107. | | | (if you have multilingual email templates.) |
  108. +--------------------+----------+--------------------------------------------------+
  109. | cc | No | list emails, will appear in ``cc`` field |
  110. +--------------------+----------+--------------------------------------------------+
  111. | bcc | No | list of emails, will appear in `bcc` field |
  112. +--------------------+----------+--------------------------------------------------+
  113. | attachments | No | Email attachments - A dictionary where the keys |
  114. | | | are the filenames and the values are either: |
  115. | | | |
  116. | | | * files |
  117. | | | * file-like objects |
  118. | | | * full path of the file |
  119. +--------------------+----------+--------------------------------------------------+
  120. | context | No | A dictionary, used to render templated email |
  121. +--------------------+----------+--------------------------------------------------+
  122. | headers | No | A dictionary of extra headers on the message |
  123. +--------------------+----------+--------------------------------------------------+
  124. | scheduled_time | No | A date/datetime object indicating when the email |
  125. | | | should be sent |
  126. +--------------------+----------+--------------------------------------------------+
  127. | priority | No | ``high``, ``medium``, ``low`` or ``now`` |
  128. | | | (send_immediately) |
  129. +--------------------+----------+--------------------------------------------------+
  130. | backend | No | Alias of the backend you want to use. |
  131. | | | ``default`` will be used if not specified. |
  132. +--------------------+----------+--------------------------------------------------+
  133. | render_on_delivery | No | Setting this to ``True`` causes email to be |
  134. | | | lazily rendered during delivery. ``template`` |
  135. | | | is required when ``render_on_delivery`` is True. |
  136. | | | This way content is never stored in the DB. |
  137. | | | May result in significant space savings. |
  138. +--------------------+----------+--------------------------------------------------+
  139. Here are a few examples.
  140. If you just want to send out emails without using database templates. You can
  141. call the ``send`` command without the ``template`` argument.
  142. .. code-block:: python
  143. from post_office import mail
  144. mail.send(
  145. ['recipient1@example.com'],
  146. 'from@example.com',
  147. subject='Welcome!',
  148. message='Welcome home, {{ name }}!',
  149. html_message='Welcome home, <b>{{ name }}</b>!',
  150. headers={'Reply-to': 'reply@example.com'},
  151. scheduled_time=date(2014, 1, 1),
  152. context={'name': 'Alice'},
  153. )
  154. ``post_office`` is also task queue friendly. Passing ``now`` as priority into
  155. ``send_mail`` will deliver the email right away (instead of queuing it),
  156. regardless of how many emails you have in your queue:
  157. .. code-block:: python
  158. from post_office import mail
  159. mail.send(
  160. ['recipient1@example.com'],
  161. 'from@example.com',
  162. template='welcome_email',
  163. context={'foo': 'bar'},
  164. priority='now',
  165. )
  166. This is useful if you already use something like `django-rq <https://github.com/ui/django-rq>`_
  167. to send emails asynchronously and only need to store email related activities and logs.
  168. If you want to send an email with attachments:
  169. .. code-block:: python
  170. from django.core.files.base import ContentFile
  171. from post_office import mail
  172. mail.send(
  173. ['recipient1@example.com'],
  174. 'from@example.com',
  175. template='welcome_email',
  176. context={'foo': 'bar'},
  177. priority='now',
  178. attachments={
  179. 'attachment1.doc': '/path/to/file/file1.doc',
  180. 'attachment2.txt': ContentFile('file content'),
  181. 'attachment3.txt': { 'file': ContentFile('file content'), 'mimetype': 'text/plain'},
  182. }
  183. )
  184. Template Tags and Variables
  185. ---------------------------
  186. ``post-office`` supports Django's template tags and variables.
  187. For example, if you put "Hello, {{ name }}" in the subject line and pass in
  188. ``{'name': 'Alice'}`` as context, you will get "Hello, Alice" as subject:
  189. .. code-block:: python
  190. from post_office.models import EmailTemplate
  191. from post_office import mail
  192. EmailTemplate.objects.create(
  193. name='morning_greeting',
  194. subject='Morning, {{ name|capfirst }}',
  195. content='Hi {{ name }}, how are you feeling today?',
  196. html_content='Hi <strong>{{ name }}</strong>, how are you feeling today?',
  197. )
  198. mail.send(
  199. ['recipient@example.com'],
  200. 'from@example.com',
  201. template='morning_greeting',
  202. context={'name': 'alice'},
  203. )
  204. # This will create an email with the following content:
  205. subject = 'Morning, Alice',
  206. content = 'Hi alice, how are you feeling today?'
  207. content = 'Hi <strong>alice</strong>, how are you feeling today?'
  208. Multilingual Email Templates
  209. ----------------------------
  210. You can easily create email templates in various different languanges.
  211. For example:
  212. .. code-block:: python
  213. template = EmailTemplate.objects.create(
  214. name='hello',
  215. subject='Hello world!',
  216. )
  217. # Add an Indonesian version of this template:
  218. indonesian_template = template.translated_templates.create(
  219. language='id',
  220. subject='Halo Dunia!'
  221. )
  222. Sending an email using template in a non default languange is
  223. also similarly easy:
  224. .. code-block:: python
  225. mail.send(
  226. ['recipient@example.com'],
  227. 'from@example.com',
  228. template=template, # Sends using the default template
  229. )
  230. mail.send(
  231. ['recipient@example.com'],
  232. 'from@example.com',
  233. template=template,
  234. language='id', # Sends using Indonesian template
  235. )
  236. Custom Email Backends
  237. ---------------------
  238. By default, ``post_office`` uses django's ``smtp.EmailBackend``. If you want to
  239. use a different backend, you can do so by configuring ``BACKENDS``.
  240. For example if you want to use `django-ses <https://github.com/hmarr/django-ses>`_::
  241. POST_OFFICE = {
  242. 'BACKENDS': {
  243. 'default': 'smtp.EmailBackend',
  244. 'ses': 'django_ses.SESBackend',
  245. }
  246. }
  247. You can then choose what backend you want to use when sending mail:
  248. .. code-block:: python
  249. # If you omit `backend_alias` argument, `default` will be used
  250. mail.send(
  251. ['recipient@example.com'],
  252. 'from@example.com',
  253. subject='Hello',
  254. )
  255. # If you want to send using `ses` backend
  256. mail.send(
  257. ['recipient@example.com'],
  258. 'from@example.com',
  259. subject='Hello',
  260. backend='ses',
  261. )
  262. Management Commands
  263. -------------------
  264. * ``send_queued_mail`` - send queued emails, those aren't successfully sent
  265. will be marked as ``failed``. Accepts the following arguments:
  266. +---------------------------+--------------------------------------------------+
  267. | Argument | Description |
  268. +---------------------------+--------------------------------------------------+
  269. | ``--processes`` or ``-p`` | Number of parallel processes to send email. |
  270. | | Defaults to 1 |
  271. +---------------------------+--------------------------------------------------+
  272. | ``--lockfile`` or ``-L`` | Full path to file used as lock file. Defaults to |
  273. | | ``/tmp/post_office.lock`` |
  274. +---------------------------+--------------------------------------------------+
  275. * ``cleanup_mail`` - delete all emails created before an X number of days
  276. (defaults to 90).
  277. +---------------------------+--------------------------------------------------+
  278. | Argument | Description |
  279. +---------------------------+--------------------------------------------------+
  280. | ``--days`` or ``-d`` | Email older than this argument will be deleted. |
  281. | | Defaults to 90 |
  282. +---------------------------+--------------------------------------------------+
  283. | ``--delete-attachments`` | Flag to delete orphaned attachment records and |
  284. | or ``-da`` | files on disk. If flag is not set, |
  285. | | on disk attachments files won't be deleted. |
  286. +---------------------------+--------------------------------------------------+
  287. You may want to set these up via cron to run regularly::
  288. * * * * * (cd $PROJECT; python manage.py send_queued_mail --processes=1 >> $PROJECT/cron_mail.log 2>&1)
  289. 0 1 * * * (cd $PROJECT; python manage.py cleanup_mail --days=30 --delete-attachments >> $PROJECT/cron_mail_cleanup.log 2>&1)
  290. Settings
  291. ========
  292. This section outlines all the settings and configurations that you can put
  293. in Django's ``settings.py`` to fine tune ``post-office``'s behavior.
  294. Batch Size
  295. ----------
  296. If you may want to limit the number of emails sent in a batch (sometimes useful
  297. in a low memory environment), use the ``BATCH_SIZE`` argument to limit the
  298. number of queued emails fetched in one batch.
  299. .. code-block:: python
  300. # Put this in settings.py
  301. POST_OFFICE = {
  302. 'BATCH_SIZE': 50
  303. }
  304. Default Priority
  305. ----------------
  306. The default priority for emails is ``medium``, but this can be altered by
  307. setting ``DEFAULT_PRIORITY``. Integration with asynchronous email backends
  308. (e.g. based on Celery) becomes trivial when set to ``now``.
  309. .. code-block:: python
  310. # Put this in settings.py
  311. POST_OFFICE = {
  312. 'DEFAULT_PRIORITY': 'now'
  313. }
  314. Log Level
  315. ---------
  316. The default log level is 2 (logs both successful and failed deliveries)
  317. This behavior can be changed by setting ``LOG_LEVEL``.
  318. .. code-block:: python
  319. # Put this in settings.py
  320. POST_OFFICE = {
  321. 'LOG_LEVEL': 1 # Log only failed deliveries
  322. }
  323. The different options are:
  324. * ``0`` logs nothing
  325. * ``1`` logs only failed deliveries
  326. * ``2`` logs everything (both successful and failed delivery attempts)
  327. Sending Order
  328. -------------
  329. The default sending order for emails is ``-priority``, but this can be altered by
  330. setting ``SENDING_ORDER``. For example, if you want to send queued emails in FIFO order :
  331. .. code-block:: python
  332. # Put this in settings.py
  333. POST_OFFICE = {
  334. 'SENDING_ORDER': ['created']
  335. }
  336. Context Field Serializer
  337. ------------------------
  338. If you need to store complex Python objects for deferred rendering
  339. (i.e. setting ``render_on_delivery=True``), you can specify your own context
  340. field class to store context variables. For example if you want to use
  341. `django-picklefield <https://github.com/gintas/django-picklefield/tree/master/src/picklefield>`_:
  342. .. code-block:: python
  343. # Put this in settings.py
  344. POST_OFFICE = {
  345. 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField'
  346. }
  347. ``CONTEXT_FIELD_CLASS`` defaults to ``jsonfield.JSONField``.
  348. Logging
  349. -------
  350. You can configure ``post-office``'s logging from Django's ``settings.py``. For
  351. example:
  352. .. code-block:: python
  353. LOGGING = {
  354. "version": 1,
  355. "disable_existing_loggers": False,
  356. "formatters": {
  357. "post_office": {
  358. "format": "[%(levelname)s]%(asctime)s PID %(process)d: %(message)s",
  359. "datefmt": "%d-%m-%Y %H:%M:%S",
  360. },
  361. },
  362. "handlers": {
  363. "post_office": {
  364. "level": "DEBUG",
  365. "class": "logging.StreamHandler",
  366. "formatter": "post_office"
  367. },
  368. # If you use sentry for logging
  369. 'sentry': {
  370. 'level': 'ERROR',
  371. 'class': 'raven.contrib.django.handlers.SentryHandler',
  372. },
  373. },
  374. 'loggers': {
  375. "post_office": {
  376. "handlers": ["post_office", "sentry"],
  377. "level": "INFO"
  378. },
  379. },
  380. }
  381. Threads
  382. -------
  383. ``post-office`` >= 3.0 allows you to use multiple threads to dramatically speed up
  384. the speed at which emails are sent. By default, ``post-office`` uses 5 threads per process.
  385. You can tweak this setting by changing ``THREADS_PER_PROCESS`` setting.
  386. This may dramatically increase the speed of bulk email delivery, depending on which email
  387. backends you use. In my tests, multi threading speeds up email backends that use HTTP based
  388. (REST) delivery mechanisms but doesn't seem to help SMTP based backends.
  389. .. code-block:: python
  390. # Put this in settings.py
  391. POST_OFFICE = {
  392. 'THREADS_PER_PROCESS': 10
  393. }
  394. Performance
  395. ===========
  396. Caching
  397. -------
  398. if Django's caching mechanism is configured, ``post_office`` will cache
  399. ``EmailTemplate`` instances . If for some reason you want to disable caching,
  400. set ``POST_OFFICE_CACHE`` to ``False`` in ``settings.py``:
  401. .. code-block:: python
  402. ## All cache key will be prefixed by post_office:template:
  403. ## To turn OFF caching, you need to explicitly set POST_OFFICE_CACHE to False in settings
  404. POST_OFFICE_CACHE = False
  405. ## Optional: to use a non default cache backend, add a "post_office" entry in CACHES
  406. CACHES = {
  407. 'post_office': {
  408. 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
  409. 'LOCATION': '127.0.0.1:11211',
  410. }
  411. }
  412. send_many()
  413. -----------
  414. ``send_many()`` is much more performant (generates less database queries) when
  415. sending a large number of emails. ``send_many()`` is almost identical to ``mail.send()``,
  416. with the exception that it accepts a list of keyword arguments that you'd
  417. usually pass into ``mail.send()``:
  418. .. code-block:: python
  419. from post_office import mail
  420. first_email = {
  421. 'sender': 'from@example.com',
  422. 'recipients': ['alice@example.com'],
  423. 'subject': 'Hi!',
  424. 'message': 'Hi Alice!'
  425. }
  426. second_email = {
  427. 'sender': 'from@example.com',
  428. 'recipients': ['bob@example.com'],
  429. 'subject': 'Hi!',
  430. 'message': 'Hi Bob!'
  431. }
  432. kwargs_list = [first_email, second_email]
  433. mail.send_many(kwargs_list)
  434. Attachments are not supported with ``mail.send_many()``.
  435. Running Tests
  436. =============
  437. To run the test suite::
  438. `which django-admin.py` test post_office --settings=post_office.test_settings --pythonpath=.
  439. You can run the full test suite with::
  440. tox
  441. or::
  442. python setup.py test
  443. Changelog
  444. =========
  445. Version 3.1.0 (2018-07-24)
  446. --------------------------
  447. * Improvements to attachments are handled. Thanks @SeiryuZ!
  448. * Added ``--delete-attachments`` flag to ``cleanup_mail`` management command. Thanks @Seiryuz!
  449. * I18n improvements. Thanks @vsevolod-skripnik and @delneg!
  450. * Django admin improvements. Thanks @kakulukia!
  451. Version 3.0.4
  452. -------------
  453. * Added compatibility with Django 2.0. Thanks @PreActionTech and @PetrDlouhy!
  454. * Added natural key support to `EmailTemplate` model. Thanks @maximlomakin!
  455. Version 3.0.2
  456. -------------
  457. - Fixed memory leak when multiprocessing is used.
  458. - Fixed a possible error when adding a new email from Django admin. Thanks @ivlevdenis!
  459. Version 3.0.2
  460. -------------
  461. - `_send_bulk` now properly catches exceptions when preparing email messages.
  462. Version 3.0.1
  463. -------------
  464. - Fixed an infinite loop bug in `send_queued_mail` management command.
  465. Version 3.0.0
  466. -------------
  467. * `_send_bulk` now allows each process to use multiple threads to send emails.
  468. * Added support for mimetypes in email attachments. Thanks @clickonchris!
  469. * An `EmailTemplate` can now be used as defaults multiple times in one language. Thanks @sac7e!
  470. * `send_queued_mail` management command will now check whether there are more queued emails to be sent before exiting.
  471. * Drop support for Django < 1.8. Thanks @fendyh!
  472. Full changelog can be found `here <https://github.com/ui/django-post_office/blob/master/CHANGELOG.md>`_.
  473. Created and maintained by the cool guys at `Stamps <https://stamps.co.id>`_,
  474. Indonesia's most elegant CRM/loyalty platform.
  475. .. |Build Status| image:: https://travis-ci.org/ui/django-post_office.png?branch=master
  476. :target: https://travis-ci.org/ui/django-post_office
  477. .. _uWSGI: https://uwsgi-docs.readthedocs.org/en/latest/