如何在 Django 中为多个收件人动态发送 send_mass_mail 的电子邮件?

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

我尝试向多个收件人发送电子邮件,但我做错了。我正在使用 for 循环从用户那里获取电子邮件地址。如果我打印这些电子邮件,这些格式为:'someone@xy.com' 并且我有不止一封。 但是,如果我尝试向他们发送电子邮件,只有一个用户收到。

每次刷新urls.py中的html都会发送邮件

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='myemail@gmail.com'


    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'),

]

获取要向其发送电子邮件的人员列表

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

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

如果您的消息没有改变,您也可以使用

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

如果你想使用群发邮件,因为它更有效率 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)