首页 > 解决方案 > 如何使 send_mail 函数发送密件抄送电子邮件 - Django REST API

问题描述

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

这是我的看法:

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)

并一一发送,但效率不高。

所以问题是:是否有任何方法可以一次向所有收件人发送电子邮件,以便他们无法看到彼此的电子邮件地址?

标签: djangoemaildjango-rest-framework

解决方案


是的。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)


推荐阅读