使用依赖于语句Django的消息发送电子邮件

时间:2017-03-09 14:57:45

标签: django email

我需要根据代码中if语句的状态向不同消息的用户发送电子邮件。目前,我发送的电子邮件如下:

send_mail(
    'Subject',
    'Body',
    'From',
    '['To']'
)

但是,我需要一种方法来改变电子邮件的正文,具体取决于用户导航if语句的方式,如下所示:

# drop down to select a, b, or c
if dropdown == 'a':
    sendmail( to b,c)
if dropdown == 'b':
    sendmail(to a,c)
if dropdown == 'c':
    sendmail(to a,b)

我可以在每个if声明中发送电子邮件,但我觉得有一种方法可以让我可以根据电子邮件的发送位置填充电子邮件模板。

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

使用列表

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

答案 1 :(得分:1)

使用变量,并根据条件更改其值。

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)

答案 2 :(得分:0)

您可以随时发送一封邮件

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])

我猜你有正确的对象,a,b,c实际上是User对象。您可以使用一些模板,并为每个模板渲染为字符串。它比视图中的字符串操作要好得多。假设你有以下

email_subject.txt

{{ recipient_name }}, this is the subject

email_body.txt(如果你要做html电子邮件,则为html)

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

From Support

您可以查看

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])