How to loop something to send in one email in Django

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, ['<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="462b3f06232b272f2a6825292b">[email protected]</a>]) 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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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, '<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b4a099bcb4b8b0b5f7bab6b4">[email protected]</a>'))


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x