Home > database >  How to send emails with send_mass_mail in Django for more than one recipients dynamically?
How to send emails with send_mass_mail in Django for more than one recipients dynamically?

Time:04-02

I try to send an email to more than one recipients but I am doing something wrong. I'm using a for loop to get the email addresses from the user. If I print the emails these are in this format: '[email protected]' and I have more than one. But if I try to send them the email, only one user gets the it.

It sends the mail every time if the html in the urls.py is refreshed.

views.py

from django.shortcuts import render
from django.core.mail import send_mass_mail
from somemodels.models import Project
import datetime
import calendar

def emails(request):
    today = datetime.date.today()
    weekday = today.weekday()
    month = datetime.date.today().month
    year = datetime.date.today().year
    cal = calendar.monthrange(year, month)[1]
    firstday = datetime.date.today().replace(day=1)
    subject='hello'
    message='how are you?'
    from_email='[email protected]'


    for p in Project.objects.raw('SELECT * FROM somemodels_project INNER JOIN auth_user ON auth_user.id = othermodel_project.permitted_users'):
        recipient_list = p.email,
        print(recipient_list)

    if (today == firstday):    
        messages = [(subject, message, from_email, [recipient]) for recipient in recipient_list]
        send_mass_mail(messages) 
    
        print('Successfully sent')
    else:
        print('Not sent') 

    return render(request, 'performance/emails.html')

urls.py

app_name = 'email'
urlpatterns = [

    path('emails/', login_required(views.emails), name='emails'),

]

CodePudding user response:

Get the list of people to send the email to

https://docs.djangoproject.com/en/4.0/topics/db/sql/

recipient_list =  Project.objects.raw(...)

If your message doesn't change you can also use

send_mail(
    subject,
    message,
    from_email,
    [r.email for r in recipient_list],
)

If you want to use mass mail because it is more efficient https://docs.djangoproject.com/en/4.0/topics/email/

messages = [(subject, message, from_email, [r.email]) for r in recipient_list]

send_mass_mail(messages) 
  • Related