LPgenerator / django-db-mailer

Django module to easily send emails/sms/tts/push using django templates stored on database and managed through the Django Admin
https://github.com/LPgenerator/django-db-mailer
GNU General Public License v2.0
256 stars 80 forks source link

send_db_mail arguments for template + template tags #71

Closed tyapkov closed 7 years ago

tyapkov commented 7 years ago

Hi guys,

What is the working example of providing arguments to send_db_mail()?

Following example is not working:

send_db_mail(
    # slug which defined on db template
    slug='welcome',

    # recipient can be list, or str separated with comma or simple string
    # 'user1@example.com' or 'user1@example.com, user2@example.com' or
    # ['user1@example.com', 'user2@example.com'] or string Mail group slug
    recipient='user1@example.com',

    **# All *args params will be accessible on template context
    {
        'username': request.user.username,
        'full_name': request.user.get_full_name(),
        'signup_date': request.user.date_joined,
        'prefix': "DbMail",
    },**
)

because: SyntaxError: positional argument follows keyword argument

Can you please write me how to pass arguments?

Also I have another question. Is it possible to use tags inside of template? I want to render url in the template with something similar to {% url ... %} Thanks!

gotlium commented 7 years ago
  1. A wrote about positional arguments here #5
  2. Yes, you can use all django tags on template.
tyapkov commented 7 years ago

Есть предложение сделать пример для документации как передавать правильно контекст в сообщении, а также другие переменные и использовать их в шаблоне. Могу это сделать, но для этого мне нужно знать как работать с переменными в шаблоне. Раньше я делал примерно так:

 def send_activation_email(self):
    context = {'user': self.user,
               'without_usernames': False,
               'protocol': get_protocol(),
               'activation_days': ACCOUNTS_REGISTRATION_ACTIVATION_DAYS,
               'activation_key': self.activation_key,
               'site': Site.objects.get_current()}

    subject = render_to_string('accounts/emails/activation_email_subject.txt', context)
    subject = ''.join(subject.splitlines())

    message = render_to_string('accounts/emails/activation_email_message.txt', context)

    send_mail(subject, message, None, EMAIL_DEFAULT_FROM_EMAIL, [self.user.email])

При этом сам шаблон выглядел так:

{% load i18n %}{% autoescape off %}
{% if not without_usernames %}{% blocktrans with user.username as username %}Dear {{ username }},{% endblocktrans %}
{% endif %}
{% blocktrans with site.name as site %}Thank you for signing up at {{ site }}.{% endblocktrans %}

{% trans "To activate your account you should click on the link below:" %}

{{ protocol }}://{{ site.domain }}{% url 'accounts:activate' activation_key %}

{% trans "Thanks for using our site!" %}

{% trans "Sincerely" %},
{{ site.name }}
{% endautoescape %}

Вопрос у меня сейчас в том, как в шаблоне использовать {% url %} тэги, а также другие переменные? Может быть скините кусочек кода из проекта, чтобы можно было разобраться? Спасибо!

gotlium commented 7 years ago
  1. шаблон уйдет в БД
  2. код изменится так
    send_db_mail(
        'activation_email_message',
               {'user': self.user,
               'without_usernames': False,
               'protocol': get_protocol(),
               'activation_days': ACCOUNTS_REGISTRATION_ACTIVATION_DAYS,
               'activation_key': self.activation_key,
               'site': Site.objects.get_current()}
    )

переменные контекста передаются как в subject так и в message. ну и обрабатывается стандартным образом для django: https://github.com/LPgenerator/django-db-mailer/blob/master/dbmail/backends/mail.py#L218

tyapkov commented 7 years ago

Все увидел и все заработало. Спасибо! Проблема была с шаблоном, а не с db_mailer. Во время тестирования возник другой вопрос, может быть баг, а может нет...При загрузке формы шаблона в админке, все html тэги шаблона сбрасываются. Не сталкивались с такой проблемой?

gotlium commented 7 years ago

логично. html вырезается, если не указан тип шаблона html (иначе текст). так же отправляется 2 типа при использовании html. это на случай когда клиент не поддерживает вложения (подробнее в доке джанги). https://github.com/LPgenerator/django-db-mailer/blob/master/dbmail/backends/mail.py#L243

tyapkov commented 7 years ago

Точно, не заметил этой опции. Во всем разобрался, завтра окончательно прикручу dm_mailer к проекту. Еще раз спасибо за помощь!

gotlium commented 7 years ago

np)