Search code examples
djangodjango-emailmass-emails

Creating Dynamic Tuple for Sending Mass Email Django using send_mass_mail


I see a lot of documentation and example to create mass email like below

message1 = ('That’s your subject #1', 
 'That’s your message body #1',
 'from@yourdjangoapp.com',
 ['to@yourbestuser1.com', 'to@yourbestuser2.com'])
message2 = ('That’s your subject #2',
 'That’s your message body #2',
 'from@yourdjangoapp.com',
 ['to@yourbestuser2.com'])
message3 = ('That’s your subject #3',
 'That’s your message body #3',
 'from@yourdjangoapp.com',
 ['to@yourbestuser3.com'])
send_mass_mail((message1, message2, message3), fail_silently=False)

I want to send mass email to N number of users returned from my queryset with the same message. I am using the code below to send mass email. However , it is very slow and would want to know if any efficient methods exists or since am using gmail for testing, its going to be slow.

def sendMassPasswordResetEmail(request):
    
    

    schoolval =  user_school.objects.filter(username=request.user.id).values_list('schoolCode',flat=True)[0]
    clsval = student_group.objects.filter(schoolCode=schoolval).values_list('classVal_id').distinct()
    student = studentclass.objects.all().prefetch_related('student_group_set__username').filter(student_group__classVal__in=clsval).distinct()
    addStudentlink = True
    #groups = student.values('student_group')
    userinschool = User.objects.filter(user_school__schoolCode=schoolval,user_type=1).values('username')
    
    html_content = render_to_string('dashboard/registration_email.html') # render with dynamic value
    text_content = strip_tags(html_content) # Strip the html tag. So people ca
    
    for recipient in userinschool:    
        subject, from_email, to = 'Account Activation xxxxx', 'xxxxxgmail.com.com',recipient.get('username')
        print(recipient.get('username'))       
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) 
        msg.attach_alternative(html_content, "text/html") 
        msg.send()
    
      
    return render(request,'dashboard/add-student.html',{'students':student, 'addStudentlink':addStudentlink})

I am unable to generate (due to lack of knowledge) dynamic tuple for send_mass_email. Any help would be appreciated.


Solution

  • You should use send_mass_mail that does exactly what you want.

    Here is an example of how to do it:

    messages = ()
    for item in items:  
        messages = messages + ((item.subject, item.message, item.from, [item.to]),)
    send_mass_mail(messages, fail_silently=False)