Passing Unique Variable when Sending E-Mail with Django

965 views Asked by At

In my Django project I have leads which belong to an organization. One of my views filters these leads by organization and then e-mails them a message. This message is in the form of an html template.

Currently this is how I do it:

# FIRST: get a list of all the emails
leads_email = []

leads = Lead.objects.filter(organization=organization)
for lead in leads:
    if lead.email != None:
        leads_email.append(lead.email)


# SECOND: Django email functions
msg = EmailMessage(subject, 
                  get_template('email_templates/campaign_email.html').render(
                        {
                            'message': message,
                        }
                    ),
                    from_email,
                    bcc=to_list)
msg.content_subtype = "html"
msg.send()

However each lead has a unique code associated with them, this field is found under lead.code. I would like to include this code in the email.

For example if [email protected]'s unique code is "test123", then I want to include that in the email to [email protected] alone. I am currently doing this by passing though a variable called message, however this is not unique and every lead gets the same thing.

Any idea on how I can accomplish this? Thanks

1

There are 1 answers

0
markwalker_ On BEST ANSWER

If you've got email content that is specific to each object, you'll have to send the emails individually rather than in bulk. So you just need to include the email code in your loop;

leads = Lead.objects.filter(organization=organization)
for lead in leads:
    if lead.email != None:
        msg = EmailMessage(
            subject, 
            get_template('email_templates/campaign_email.html').render(
                {
                    'message': message,
                    'code': lead.code
                }
            ),
            from_email,
            [lead.email, ]
        )
        msg.content_subtype = "html"
        msg.send()