如果聊天中有新消息,我想向聊天中的每个人(消息作者除外)发送通知。我想发一封邮件给所有人,这样就没有人能看到其他人的邮箱地址(抄送盲)。我该怎么做呢?
这是我的观点:
class WriteMessageCreateAPIView(generics.CreateAPIView):
permission_classes = [IsAuthenticated, IsParticipant]
serializer_class = MessageSerializer
def perform_create(self, serializer):
...
chat = serializer.validated_data['chat']
chat_recipients = chat.participants.exclude(id=self.request.user.id)
for participant in chat_recipients:
MessageRecipient.objects.create(message_id=new_message.id, recipient_id=participant.id)
send_new_message_notification(chat.id, new_message.author, chat_recipients)
在这里,电子邮件一次发送给所有收件人,但以抄送的形式(每个人都可以看到彼此的电子邮件地址)。
send_mail函数:
def send_new_message_notification(chat_id, sender: User, recipients):
link = BASE_URL + '/messaging/chat/%s/messages' % chat_id
send_email(
subject='You have a new message',
message='Click the link below to view the message:', link),
from_email='some_email@email.com',
recipient_list=recipients
)
是的,我可以在视图部分这样做:
for participant in chat_recipients:
MessageRecipient.objects.create(message_id=new_message.id, recipient_id=participant.id)
send_new_message_notification(chat.id, new_message.author, participant)
并逐个发送,但效率不高。
所以问题是:有没有一种方法可以同时向所有收件人发送电子邮件,使他们无法看到彼此的电子邮件地址?
是。Django有一个send_mass_mail
函数就是为了这个目的。你可以在这里查看文档。
# This is more efficient, because it hits the database only
# once instead of once for each new MessageRecipient
message_recipients = [MessageRecipient(message_id=new_message.id, recipient_id=participant.id) for participant in chat_recipients]
MessageRecipient.objects.bulk_create(message_recipients)
# This will send separate emails, but will only make
# one connection with the email server so it will be
# more efficient
link = BASE_URL + '/messaging/chat/%s/messages' % chat.id
emails = (('You have a new message',
f'Click the link below to view the message: {link}',
'some_email@email.com',
[recepient]
) for recepient in chat_recepients)
send_mass_mail(emails, fail_silently=False)