-1

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, ['my@email.com]) 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?

RlM
  • 183
  • 12
  • Does this answer your question? [How do I concatenate items in a list to a single string?](https://stackoverflow.com/questions/12453580/how-do-i-concatenate-items-in-a-list-to-a-single-string) – outis Apr 30 '22 at 08:36

1 Answers1

0

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, 'my@email.com'))
vale
  • 91
  • 6
  • Thank you, I tried it but I've got an error message: `for subject, message, sender, recipient in datatuple ValueError: not enough values to unpack (expected 4, got 1)` – RlM Apr 30 '22 at 07:48
  • @RlM my fault. send_mass_mail argument should be a data tuple. Updated `send_mass_mail((subject, message, from_email, 'my@email.com'))` – vale Apr 30 '22 at 08:02