如何使 send_mail 函数发送密件抄送电子邮件 - Django REST API

时间:2021-02-11 19:46:08

标签: django email django-rest-framework

如果聊天中有新消息,我想向聊天中的每个人(消息作者除外)发送通知。我想向所有人发送一封电子邮件,以便没有人可以看到其他人的电子邮件地址(bcc-blind 抄送)。我该怎么做?

这是我的观点:

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)

并且一个一个发送,但是效率不高。

那么问题是:有没有什么方法可以同时向所有收件人发送电子邮件,这样他们就无法看到彼此的电子邮件地址?

1 个答案:

答案 0 :(得分:0)

是的。 Django 有一个 send_mass_mail 函数就是为了这个目的。您可以查看文档 here

# 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)