Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jam0r's avatar
Level 8

Storing sent emails in the database

So I want a way of storing sent emails inside of the database for future reference. I've hooked into the MessageSending event and am using the following handle in my listener.

    public function handle(MessageSending $event)
    {
        $message = $event->message;

        return dd($message);

        Email::create([
            'to' => !$message->getHeaders()->get('To') ? null : $message->getHeaders()->get('To')->getFieldBody(),
            'bcc' => !$message->getHeaders()->get('Bcc') ? null : $message->getHeaders()->get('Bcc')->getFieldBody(),
            'subject' => $message->getHeaders()->get('Subject')->toString(),
            'body' => $this->getMimeEntityString($message),
        ]);
    }

    protected function getMimeEntityString(\Swift_Mime_MimeEntity $entity)
    {
        $string = (string) $entity->getHeaders().PHP_EOL.$entity->getBody();

        foreach ($entity->getChildren() as $children) {
            $string .= PHP_EOL.PHP_EOL.$this->getMimeEntityString($children);
        }
        
        return $string;
    }

Is this the best (easiest and quickest) way of doing this?

0 likes
5 replies
jasperstaats's avatar

I don't see any reason to assume its a bad way. We use it the same method but use a column called : full_email with type LONGTEXT. Includes the full email with the full html. This way you wont destroy the full layout of the email.

How do you wanna handle attachments in an email?

Also dont forget to save the flags like "READ" , "UNREAD" , "NEW".

Jam0r's avatar
Level 8

Hadn't thought about recording attachments but now that you mention it, that would be useful as well.

I was doing this just to record basic emails but we often send emails to users with statements and invoices attached so would be good to see the email exactly how it's sent.

Also, although I am recording the 'to' part of the email, I would like to link the email to the user(s) by the way of a pivot table but i'm wondering how to get the $user automatically?

jasperstaats's avatar

Well we've build something related so I can try to help out. But how do you mean "how to get the $user automatically"?

Jam0r's avatar
Level 8

For example, when sending an email:-

Mail::to($request->user())->send(new OrderShipped($order));

Is there any way to get the user from the 'to' later on? I know I could add $user to the OrderShipped example but was wondering if there was an easier, more fluid/automatic way.

This would be so I could attach the email and user via a pivot table in case they ever changed their email address.

eugenefvdm's avatar

5 years on and this still looks like a really good solution which I'm about to implement.

Please or to participate in this conversation.