PHPackages                             baraja-core/doctrine-mail-message - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. baraja-core/doctrine-mail-message

ActiveLibrary[Database &amp; ORM](/categories/database)

baraja-core/doctrine-mail-message
=================================

Converter Mail message to Doctrine entity.

v2.1.3(4y ago)139.4k↓100%1PHPPHP ^8.0CI failing

Since Sep 19Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/baraja-core/doctrine-mail-message)[ Packagist](https://packagist.org/packages/baraja-core/doctrine-mail-message)[ Docs](https://github.com/baraja-core/doctrine-mail-message)[ RSS](/packages/baraja-core-doctrine-mail-message/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (14)Versions (17)Used By (1)

Doctrine Mail Message
=====================

[](#doctrine-mail-message)

[![Integrity check](https://github.com/baraja-core/doctrine-mail-message/workflows/Integrity%20check/badge.svg)](https://github.com/baraja-core/doctrine-mail-message/workflows/Integrity%20check/badge.svg)

A robust PHP library that provides bidirectional conversion between Nette Mail messages and Doctrine entities. This package allows you to persist email messages in a database, enabling email queuing, logging, retry mechanisms, and comprehensive email history tracking.

✨ Key Features
--------------

[](#-key-features)

- **Bidirectional Conversion** - Seamlessly convert `Nette\Mail\Message` to Doctrine entity and back
- **Full Email Support** - Handles all standard email fields: From, To, CC, BCC, Reply-To, Return-Path, Priority
- **Attachment Management** - Automatic serialization and storage of file attachments with content-hash based deduplication
- **Tracking Support** - Automatic injection of pair tokens for email tracking and pairing
- **Nette Integration** - First-class support for Nette Framework via DI extension
- **Type Safety** - Full PHP 8.0+ type declarations with PHPStan level 9 verification

🏗️ Architecture Overview
------------------------

[](#️-architecture-overview)

The library follows a clean, service-oriented architecture with clear separation of concerns:

```
┌─────────────────────────────────────────────────────────────────┐
│                      Your Application                           │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                       MessageEntity                             │
│  ┌─────────────────┐              ┌─────────────────────────┐  │
│  │   toEntity()    │─────────────▶│    DoctrineMessage      │  │
│  │   toMessage()   │◀─────────────│    (Doctrine Entity)    │  │
│  └─────────────────┘              └─────────────────────────┘  │
│           │                                    │                │
│           ▼                                    ▼                │
│  ┌─────────────────┐              ┌─────────────────────────┐  │
│  │     Helpers     │              │   Attachment Storage    │  │
│  │ (Header Format) │              │   (File System)         │  │
│  └─────────────────┘              └─────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     Nette\Mail\Message                          │
│                   (Standard Mail Object)                        │
└─────────────────────────────────────────────────────────────────┘

```

🧩 Components
------------

[](#-components)

### DoctrineMessage Entity

[](#doctrinemessage-entity)

The core Doctrine entity (`DoctrineMessage`) maps to the `core__email_message` database table and stores:

FieldTypeDescription`id`integerAuto-generated primary key`from`stringSender email address`to`stringPrimary recipient`subject`stringEmail subject line`htmlBody`text (nullable)HTML content of the email`textBody`text (nullable)Plain text content`cc`jsonArray of CC recipients`bcc`jsonArray of BCC recipients`replyTo`jsonArray of Reply-To addresses`returnPath`string (nullable)Return path for bounces`priority`smallintEmail priority (default: normal)`attachments`jsonAttachment metadata array### MessageEntity Service

[](#messageentity-service)

The main service class responsible for:

- Converting `Nette\Mail\Message` objects to `DoctrineMessage` entities via `toEntity()`
- Converting `DoctrineMessage` entities back to `Nette\Mail\Message` via `toMessage()`
- Managing attachment serialization/deserialization
- Automatic entity persistence during conversion

### Helpers

[](#helpers)

A static utility class providing:

- `formatHeader()` - Formats email headers from various array formats to string representation
- `getFileNameByContentDisposition()` - Extracts filename from Content-Disposition header
- `processHtmlMail()` - Injects tracking pair tokens into HTML email body

### DI Extension

[](#di-extension)

The `DoctrineMailMessageExtension` provides automatic integration with Nette Framework:

- Registers entity paths for Doctrine ORM annotation discovery
- Creates attachment storage directory in temp path
- Registers `MessageEntity` as a service

📦 Installation
--------------

[](#-installation)

It's best to use [Composer](https://getcomposer.org) for installation, and you can also find the package on [Packagist](https://packagist.org/packages/baraja-core/doctrine-mail-message) and [GitHub](https://github.com/baraja-core/doctrine-mail-message).

To install, simply use the command:

```
$ composer require baraja-core/doctrine-mail-message
```

You can use the package manually by creating an instance of the internal classes, or register a DIC extension to link the services directly to the Nette Framework.

### Requirements

[](#requirements)

- PHP 8.0 or higher
- Doctrine ORM 2.7+
- Doctrine DBAL 3.2+
- Nette Framework 3.0+ (for DI integration)

⚙️ Configuration
----------------

[](#️-configuration)

### Nette Framework Integration

[](#nette-framework-integration)

Register the extension in your NEON configuration file:

```
extensions:
    doctrineMailMessage: Baraja\DoctrineMailMessage\DoctrineMailMessageExtension
```

The extension will automatically:

1. Register the entity path for Doctrine annotations
2. Create the `emailer-attachments` directory in your temp folder
3. Register the `MessageEntity` service in the DI container

### Manual Configuration

[](#manual-configuration)

If not using Nette Framework, create the service manually:

```
use Baraja\DoctrineMailMessage\MessageEntity;
use Doctrine\ORM\EntityManagerInterface;

$messageEntity = new MessageEntity(
    attachmentBasePath: '/path/to/temp/emailer-attachments',
    entityManager: $entityManager, // Your EntityManagerInterface instance
    logger: $logger, // Optional PSR-3 LoggerInterface
);
```

🚀 Basic Usage
-------------

[](#-basic-usage)

### Converting Mail Message to Entity

[](#converting-mail-message-to-entity)

```
use Nette\Mail\Message;
use Baraja\DoctrineMailMessage\MessageEntity;

// Create a standard Nette Mail message
$message = new Message;
$message->setFrom('sender@example.com', 'Sender Name')
    ->addTo('recipient@example.com', 'Recipient Name')
    ->setSubject('Hello World')
    ->setHtmlBody('This is an HTML email.')
    ->setBody('This is a plain text email.');

// Convert to Doctrine entity (automatically persisted)
/** @var MessageEntity $messageEntity */
$doctrineMessage = $messageEntity->toEntity($message);

// Entity is now persisted and has an ID
echo $doctrineMessage->getId(); // e.g., 42
```

### Converting Entity Back to Mail Message

[](#converting-entity-back-to-mail-message)

```
use Baraja\DoctrineMailMessage\DoctrineMessage;

// Load entity from database
$doctrineMessage = $entityManager->find(DoctrineMessage::class, 42);

// Convert back to Nette Mail Message
$message = $messageEntity->toMessage($doctrineMessage);

// Now you can send it via any Nette mailer
$mailer->send($message);
```

### Working with Attachments

[](#working-with-attachments)

Attachments are automatically handled during conversion:

```
$message = new Message;
$message->setFrom('sender@example.com')
    ->addTo('recipient@example.com')
    ->setSubject('Document Attached')
    ->setHtmlBody('Please find the document attached.')
    ->addAttachment('document.pdf', $pdfContent, 'application/pdf');

// Attachments are serialized to filesystem
$doctrineMessage = $messageEntity->toEntity($message);

// When converting back, attachments are restored
$restoredMessage = $messageEntity->toMessage($doctrineMessage);
```

Attachment files are stored in the configured temp directory with content-hash based naming for deduplication.

### Handling CC, BCC, and Reply-To

[](#handling-cc-bcc-and-reply-to)

```
$message = new Message;
$message->setFrom('sender@example.com')
    ->addTo('primary@example.com')
    ->addCc('cc1@example.com')
    ->addCc('cc2@example.com')
    ->addBcc('bcc@example.com')
    ->addReplyTo('reply@example.com')
    ->setSubject('Multi-recipient Email');

$doctrineMessage = $messageEntity->toEntity($message);

// Access stored recipients
echo $doctrineMessage->getTo();           // primary@example.com
print_r($doctrineMessage->getCc());       // ['cc1@example.com', 'cc2@example.com']
print_r($doctrineMessage->getBcc());      // ['bcc@example.com']
print_r($doctrineMessage->getReplyTo());  // ['reply@example.com']
```

### Email Priority

[](#email-priority)

```
use Nette\Mail\Message;

$message = new Message;
$message->setPriority(Message::HIGH); // HIGH, NORMAL, or LOW

$doctrineMessage = $messageEntity->toEntity($message);
echo $doctrineMessage->getPriority(); // 1 (HIGH)
```

### Cleaning Up Attachment Storage

[](#cleaning-up-attachment-storage)

After successfully sending an email or when no longer needed:

```
// Remove attachment files for a specific message
$messageEntity->invalidAttachmentStorage($doctrineMessage);
```

### Custom Attachment Directory Mode

[](#custom-attachment-directory-mode)

```
// Set custom directory permissions (default is 0777)
$messageEntity->setDefaultAttachmentDirectoryMode(0755);
```

🔍 Email Tracking
----------------

[](#-email-tracking)

The library automatically injects a hidden tracking token into HTML emails when converting from entity to message:

```
42_2024-01-15
```

This token contains the message ID and date, enabling:

- Email open tracking (when combined with tracking pixel)
- Pairing sent emails with responses
- Email delivery verification

📋 Database Schema
-----------------

[](#-database-schema)

The entity creates the following table structure:

```
CREATE TABLE core__email_message (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `from` VARCHAR(255) NOT NULL,
    `to` VARCHAR(255) NOT NULL,
    subject VARCHAR(255) NOT NULL,
    html_body LONGTEXT,
    text_body LONGTEXT,
    cc JSON NOT NULL,
    bcc JSON NOT NULL,
    reply_to JSON NOT NULL,
    return_path VARCHAR(255),
    priority SMALLINT NOT NULL DEFAULT 3,
    attachments JSON NOT NULL,
    INDEX core__email_message_subject (id, subject)
);
```

⚠️ Error Handling
-----------------

[](#️-error-handling)

The library provides clear error messages for common issues:

- **Missing From Address**: Triggers error in web context, throws exception in CLI
- **Missing Recipient**: Triggers warning for potential issues
- **Invalid Attachment Path**: Throws `RuntimeException` or logs via PSR-3 logger
- **Missing Temp Directory**: Throws `RuntimeException` with configuration hints

🧪 Testing
---------

[](#-testing)

Run static analysis:

```
composer phpstan
```

👤 Author
--------

[](#-author)

**Jan Barášek**

- Website:
- GitHub:

📄 License
---------

[](#-license)

`baraja-core/doctrine-mail-message` is licensed under the MIT license. See the [LICENSE](https://github.com/baraja-core/doctrine-mail-message/blob/master/LICENSE) file for more details.

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance52

Moderate activity, may be stable

Popularity24

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 95.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~44 days

Recently: every ~3 days

Total

13

Last Release

1525d ago

Major Versions

v1.2.0 → v2.0.02021-02-10

PHP version history (4 changes)v1.0.0PHP &gt;=7.1.0

v1.1.0PHP &gt;=7.4.0

v1.2.0PHP ^7.4 || ^8.0

v2.0.0PHP ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3382204?v=4)[baraja](/maintainers/baraja)[@baraja](https://github.com/baraja)

---

Top Contributors

[![janbarasek](https://avatars.githubusercontent.com/u/4738758?v=4)](https://github.com/janbarasek "janbarasek (40 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (1 commits)")

---

Tags

doctrinemailmessageserializationstore

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/baraja-core-doctrine-mail-message/health.svg)

```
[![Health](https://phpackages.com/badges/baraja-core-doctrine-mail-message/health.svg)](https://phpackages.com/packages/baraja-core-doctrine-mail-message)
```

###  Alternatives

[scienta/doctrine-json-functions

A set of extensions to Doctrine that add support for json query functions.

58523.9M36](/packages/scienta-doctrine-json-functions)[damienharper/auditor-bundle

Integrate auditor library in your Symfony projects.

4542.8M](/packages/damienharper-auditor-bundle)[sonata-project/entity-audit-bundle

Audit for Doctrine Entities

644989.8k1](/packages/sonata-project-entity-audit-bundle)[kdyby/doctrine

Doctrine integration into Nette Framework

1091.0M86](/packages/kdyby-doctrine)[bartlett/php-compatinfo-db

Reference Database of all functions, constants, classes, interfaces on PHP standard distribution and about 110 extensions

1183.0k1](/packages/bartlett-php-compatinfo-db)[heymoon/doctrine-psql-enum

Store PHP native enums as PostgeSQL custom enum types

254.9k](/packages/heymoon-doctrine-psql-enum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
