【问题标题】:Sending emails with messages dependent on if statements Django发送带有依赖于 if 语句 Django 的消息的电子邮件
【发布时间】:2017-03-09 14:57:44
【问题描述】:

我需要根据我的代码中 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 声明中发送电子邮件,但我觉得有一种方法可以让我拥有一个电子邮件模板,我可以根据电子邮件的发送位置填充该模板。

感谢您的帮助!

【问题讨论】:

    标签: django email


    【解决方案1】:

    使用列表

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

    【讨论】:

    • 感谢您的回复!我如何将电子邮件正文添加到这些邮件中,因为每个 if 语句中的电子邮件正文都不同?还是这超出了范围?
    • 您也可以对正文使用一些类似的机制,但由于这回答了您的原始问题,请标记为正确并发布新问题,但请务必发布stackoverflow.com/help/mcve
    • 啊,您的意见很好,我确信我可以解决我的问题,再次感谢您的帮助!
    【解决方案2】:

    使用变量,并根据条件更改它们的值。

    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)
    

    【讨论】:

    • 最后的sendmail一定要指定收件人吗?
    • 那是很多代码,如果收件人的数量增加,它会增加。
    • 而您正在发送给两个不正确的收件人,这种方法的错误是常态而不是例外
    【解决方案3】:

    您总是可以一次发送一封邮件

    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 实际上是用户对象。您可以使用一些模板,并将每个模板呈现为字符串。它比视图中的字符串操作要好得多。假设你有关注

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 2021-10-25
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多