用于排队发送电子邮件的可重用django应用程序(apsl/django-mailer-2分叉,未维护)
django-mailer-2的Python项目详细描述
django-mailer-2是异步的,因此除了将邮件放入队列之外 需要定期通知它清除队列并实际发送邮件。
后者是通过命令扩展完成的。
将邮件放入队列(django 1.2或更高版本)
在setting s.py中,配置django的电子邮件后端设置,如下所示:
EMAIL_BACKEND = ‘django_mailer.smtp_queue.EmailBackend’
如果您不需要邮件优先级支持,您可以调用 你通常会在Django:
send_mail(subject, message_body, settings.DEFAULT_FROM_EMAIL, recipients)
如果需要按优先级排列的邮件,请创建电子邮件的实例 并在headers参数中指定{x-mail-queue-priority':'<;value>;'}, 其中,<;value>;是:
‘now’ - do not queue, send immediately ‘high’ - high priority ‘normal’ - standard priority - this is the default. ‘low’ - low priority
如果未指定优先级,则邮件将以“正常”优先级发送
将邮件放入队列(django 1.1或更早版本)
因为django mailer当前使用的函数签名与django的相同 核心邮件支持您可以在代码中执行以下操作:
# favour django-mailer-2 but fall back to django.core.mail from django.conf import settings if "django_mailer" in settings.INSTALLED_APPS: from django_mailer import send_mail else: from django.core.mail import send_mail
然后打电话给send_mail,就像在django一样:
send_mail(subject, message_body, settings.DEFAULT_FROM_EMAIL, recipients)
此外,您还可以发送^{tt2}中指定的所有管理员$ 通过调用设置:
mail_admins(subject, message_body)
或通过调用MANAGERS设置中定义的所有管理器:
mail_managers(subject, message_body)
命令扩展名
在已安装的应用程序中使用mailer,将有四个新的manage.py命令 您可以运行:
- ^{tt4}$ will clear the current message queue. If there are any failures, they will be marked deferred and will not be attempted again by ^{tt4}$.
- ^{tt6}$ will move any deferred mail back into the normal queue (so it will be attempted again on the next ^{tt4}$).
- ^{tt8}$ will delete mails created before an X number of days (defaults to 90).
- ^{tt9}$ the intent of this commant is to allow systems as nagios to
- be able to ask the queue about its status. It returns as string with than can be parses as ^{tt10}$
您可能希望通过cron将这些设置为定期运行:
* * * * * (cd $PROJECT; python manage.py send_mail >> $PROJECT/cron_mail.log 2>&1) 0,20,40 * * * * (cd $PROJECT; python manage.py retry_deferred >> $PROJECT/cron_mail_deferred.log 2>&1) 0 1 * * * (cd $PROJECT; python manage.py cleanup_mail --days=30 >> $PROJECT/cron_mail_cleanup.log 2>&1)
此操作尝试每分钟发送一封邮件,每20分钟重试一次失败 并将每天运行清理任务来清理之前创建的所有邮件 30天
manage.py send_mail使用锁文件以防清除队列 长于调用manage.py send_mail之间的间隔。
注意,如果您的项目位于virtualenv中,则还必须执行 这个命令来自virtualenv当然,如果你是 用cron执行它。