backend for test environment an email backend for use during test sessions the test connection stores email messages in a dummy outbox rather than sending them out on the wire the dummy outbox is accessible through the outbox instance attribute redirect messages to the dummy outbox msgcount 0 for message in messages message triggers header validation message message mail outbox appendcopy deepcopymessage msgcount 1 return msgcount an email backend for use during test sessions the test connection stores email messages in a dummy outbox rather than sending them out on the wire the dummy outbox is accessible through the outbox instance attribute redirect messages to the dummy outbox message triggers header validation
import copy

from django.core import mail
from django.core.mail.backends.base import BaseEmailBackend


class EmailBackend(BaseEmailBackend):
    

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not hasattr(mail, "outbox"):
            mail.outbox = []

    def send_messages(self, messages):
        
        msg_count = 0
        for message in messages:  
            message.message()
            mail.outbox.append(copy.deepcopy(message))
            msg_count += 1
        return msg_count