[Answered ]-Sending emails with messages dependent on if statements Django

1👍

Use a list

recipients = ['a','b','c']
recipients.remove('drop down')
sendmail(recipients)
👤e4c5

1👍

Use variables, and change their values depending on the condition.

subject = ''
body = ''
from = 'domain@domain.com'
recipients = ['a','b','c']

if dropdown == 'a':
    subject = 'Subject A'
    body = 'Body A'
    recipients = ['a','b','c']
elif dropdown == 'b':
    subject = 'Subject B'
    body = 'Body B'
    recipients = ['b']
elif dropdown == 'c':
    subject = 'Subject C'
    body = 'Body C'
    recipients = ['a','b']

sendmail( subject, body, from)

0👍

You could always send one mail at a time

sender = 'domain@domain.com'
recipients = ['a', 'b', 'c']
for recipient in recipients:
    if recipient == dropdown:
        continue
    subject = 'Subject {}'.format(recipient.upper())
    body = 'Email body for {}'.format(recipient.upper())
    sendmail(subject, body, sender, [recipient])

I’m guessing you have proper object and a,b,c are actually User objects. You could use some templates, and render to string for each one. It’s much better than string manipulation in the view. Suppose you have the follow

email_subject.txt

{{ recipient_name }}, this is the subject

email_body.txt (and html if you’ll be doing html emails)

Hey {{ recipient_name }},
This is the email specially for you

From Support

You view could be

sender = 'domain@domain.com'
recipients = get_recipients_but_exclude(dropdown)
for recipient in recipients:
    subject = render_to_string('email_subject.txt', {'recipient_name': recipient.get_full_name()})
    body = render_to_string('email_body.txt', {'recipient_name': recipient.get_full_name()})
    sendmail(subject, body, sender, [recipient])

Leave a comment