Home > Mobile >  How to loop something to send in one email in Django
How to loop something to send in one email in Django

Time:04-30

I like to send email to myself that contains the name of users who matches the criteria. My problem is that if I use the for loop in the mass_mail it sends every results in separated emails. So if I have 6 results it sends the email 6 times containing one results in every emails: (I am using the mass_mail because in the future I like to send emails to more users not just me.)

user_weekly.py

from django.core.management.base import BaseCommand
from xy.models import Profile
from django.core.mail import send_mass_mail

recipient_list = Profile.objects.raw('SELECT * FROM auth_user LEFT JOIN xy_profile ON auth_user.id = xy_profile.user_id WHERE email = 1')

messages = [(subject, 'Hello! Users are the following:'   r.last_name, from_email, ['[email protected]]) for r in recipient_list]
send_mass_mail(messages)

How can I reach that to send all the results in one email and not 6 separate emails in this case?

I also tried that to make a variable like this: reclist = r.last_name but in this case it sends only one email with only one user's name.

What should I do to get all the user's names in one email?

CodePudding user response:

You can try looping the string generation as follows

from django.core.management.base import BaseCommand
from xy.models import Profile
from django.core.mail import send_mass_mail

recipient_list = Profile.objects.raw('SELECT * FROM auth_user LEFT JOIN xy_profile ON auth_user.id = xy_profile.user_id WHERE email = 1')

message='Hello! Users are the following: '
for r in recipient_list:
  message =r.last_name ", "

message=message[2:]

send_mass_mail((subject, message, from_email, '[email protected]'))
  • Related