PHPackages                             net-tools/mailing - 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. [Mail &amp; Notifications](/categories/mail)
4. /
5. net-tools/mailing

ActiveLibrary[Mail &amp; Notifications](/categories/mail)

net-tools/mailing
=================

Composer library to handle emails with PHP

1.14.0(2y ago)01.0k5MITPHPPHP &gt;= 7.2.0

Since Dec 1Pushed 2y ago1 watchersCompare

[ Source](https://github.com/net-tools/mailing)[ Packagist](https://packagist.org/packages/net-tools/mailing)[ RSS](/packages/net-tools-mailing/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (5)Versions (139)Used By (5)

net-tools/mailing
=================

[](#net-toolsmailing)

Composer library to send emails with PHP
----------------------------------------

[](#composer-library-to-send-emails-with-php)

This package contains all classes required to easily build e-mails with PHP, in an object-oriented way.

Attachments and embeddings are supported.

Setup instructions
------------------

[](#setup-instructions)

To install net-tools/mailing package, just require it through composer : `require net-tools/mailing:^1.0.0`.

How to use ?
------------

[](#how-to-use-)

### Quick email sending

[](#quick-email-sending)

To send an email in an easy way, just get an instance of `Mailer` with default email sending strategy, and call `expressSendmail` method. If no attachments to send, omit the last parameter.

```
Mailer::getDefault()->expressSendmail(
  'This is a test',
  'from-user@test.com',
  'recipient@test.com',
  'This is a subject',
  array('/home/tmp/invoice.pdf')
);
```

Email technical parts (text/plain, text/html, multipart/alternative, multipart/mixed) will be created automatically ; the default email sending strategy send emails through PHP built-in Mail() function.

### Build emails

[](#build-emails)

If you want to have more control when sending emails, you may build them with Mailer :

```
$mail = Mailer::addTextHtmlFromText('\*\*This is a\*\* test');
$mail = Mailer::addAttachment($mail, '/home/tmp/invoice.pdf', 'your_invoice.pdf', 'application/pdf');
Mailer::getDefault()->sendmail($mail, 'from-user@test.com', 'recipient@test.com', 'This is a subject');
```

To send emails with SMTP protocol (or any other email sending strategy in the MailSenders subfolder), create the Mailer (instead of getting it throught `getDefault`) with the appropriate MailSender object

```
$smtpmailer = new Mailer(new MailSenders\SMTP(array('host'=>'mysmtphost.com', 'username'=>'user', 'password'=>'1234')));
$smtpmailer->sendmail($mail, 'from-user@test.com', 'recipient@test.com', 'This is a subject');
```

### Parse an EML file/string to create a MailContent object

[](#parse-an-eml-filestring-to-create-a-mailcontent-object)

Sometimes you have an email and you want to display it on screen. However, you can't echo the raw content. You have to parse the email content to extract the appropriate part (generally, the text/html part) and if necessary the attachments (multipart/mixed part).

To parse the email, just use the EmlReader class and the `fromString` or `fromFile` static methods. They will return a `MailContent` object :

```
// assuming that $email is a very simple email with a multipart/alternative content
$mail = EmlReader::parseString($email);

// this line prints MailMultipart (class name of the MailContent object)
echo get_class($mail);

// the following lines extract the text/plain and text/html sub-parts
$textplain_content = $mail->getPart(0)->toString();
$htmlpart_content = $mail->getPart(1)->toString();
```

If your email contains attachments or embeddings, don't forget to call `destroy` static method to delete temporary files created during parsing to store attachments and embeddings :

```
EmlReader::destroy($mail);
```

### Send with queues

[](#send-with-queues)

Sometimes we don't want to send a lot of emails in one shot, and we may want to queue them somewhere and then send them later, maybe through batches. This is the purpose of `MailSenderQueue` subfolder. It contains a `Store` and `Queue` classes ; the first one is the facade of queue subsystem, the second stands for a given queue.

To queue items :

```
// create a Store object to manage queues
$store = new MailSenderQueue\Store('~/home/path_to_queue_subsystem_root');

// create a new queue, which sends emails through batches of 75 items
$queue = $store->createQueue('title_of_queue', 75);
$id = $queue->id;

// create an email content with text/plain and text/html parts
$mail = Mailer::addTextHtmlFromText('\*\*This is a\*\* test');

// then send email (of course this last line is usually called within a loop, to queue all items at once
$queue->push($mail, 'sender@domain.tld', 'recipient_here@domain.tld', 'Email subject here');
```

Then later on, maybe in another script/call :

```
// reopen the same store
$store = new MailSenderQueue\Store('~/home/path_to_queue_subsystem_root');

// getting queue with `$id` (saved from above call)
$queue = $store->getQueue($id);

// send a batch
$queue->send(Mailer::getDefault());
```

Please check API reference for full details about Store and Queue objects (deleting queues, dealing with errors, listing queues and recipients).

### Managing mailsenders strategies

[](#managing-mailsenders-strategies)

The Mailer object, when constructed, accepts a `MailSenders\MailSenderIntf` object, which is a strategy to send the email through. It can be `MailSenders\PHPMail` (to use the built-in `mail()` function) or `MailSenders\SMTP`. Each strategy may have some parameters (for SMTP, those are the host/user/password data).

Sometimes, there are multiple SMTP strategies (to send emails through several hosts). To deals with all those sending strategies, we have created a `MailSendersFacade` class :

- data (strategies parameters) is stored in a JSON string
- strategy list is stored in a PHP array as strings

Json and strings makes it possible to update parameters without too much trouble, and can be stored in a file, a database or hard-coded. Secondly, the creation of mail sending strategy is simplified, as all parameters are already defined in the Json data ; we just have to call a method to fetch the current strategy, initialized with proper parameters.

To create the facade object (this is the one we will be dealing with to list strategies or get one ready to use with `Mailer` class) :

```
// list of strategies with an optionnal paramaters set name
$msenders = ['SMTP:params1', 'PHPMail'];

// setting data for all strategies (json-formatted string)
$msdata = '{"SMTP:params1":{"className":"SMTP","host":"value1","username":"value2","password":"value3"}, "PHPMail":{}}';

// active strategy
$ms = 'SMTP:params1';

// create the facade object, through a list of sending strategies proxies (we don't create real `MailSenders\MailSenderIntf` objects), described with json structure
$f = MailSendersFacade\Facade::facadeProxiesFromJson($msenders, $msdata, $ms);

// ... do some stuff such as listing mail senders

// now, get the active mail sender and create the concrete `MailSenders\MailSenderIntf` object, passing it to Mailer constructor
$m = new Mailer($f->getActiveMailSender());
```

The typical use case of `MailSendersFacade` class is :

- listing mail sending strategies to the end-user : call `getProxies()` method on `Facade` object
- get the current mail sending strategy proxy : call `getActiveProxy()` method on `Facade` object
- get a real MailSender object, based on the current strategy proxy, initialized with required parameters : call `getActiveMailSender()` method on `Facade` object (the parameters defined in the Json data are automatically applied)

A word about proxies here. In this facade design pattern, we list mail sending strategies (use case : present a list of strategies and allow the end-user to choose one) ; however, creating real instances of MailSender classes (such as `MailSenders\SMTP`) is not really useful here, as we only want a list of strategies and their parameters, nothing less, nothing more. So we use proxies, that is to say objects standing for the real sending strategies in the facade design pattern ; those proxies are lightweight, so this is perfect for the use case. We also have a special kind of proxies, `Proxies\Quota` class, that makes it possible to log each mail sent with the strategy and computes quotas (the implementation of quotas has to be coded, but we provide a `PdoQuotaInterface` that may be a start to log on a database). When we do need the real mail sending strategy, we call `getMailSender()` on a proxy object, it creates the real object based on parameters provided un json data, and we get an object ready to use with `Mailer` constructor.

### Sending through `MailSenderHelpers\MailSenderHelper`

[](#sending-through-mailsenderhelpersmailsenderhelper)

Sometimes, creating the email content, adding the BCC, subject, replyTo headers or dealing with queues can be tough. The MailSenderHelpers subsystem is here to abstract all this.

```
$mailer = Mailer::getDefault();

// first, we create a helper object, with minimum parameters (mailer object, body content, sender, recipient subject, optional parameters)
$msh = new MailSenderHelpers\MailSenderHelper($mailer, 'raw mail as text', 'text/plain', 'from@me.com', 'subject of email', $params);
// OR : $msh = new MailSenderHelpers\MailSenderHelper($mailer, 'mail as html', 'text/html', 'from@me.com', 'subject of email', $params);

// prepare the mail : checking required parameters set, building text/html and text/plain parts (from respectively text/plain or text/html body content)
$mailContent = $msh->render(null);

// send the email rendered
$msh->send($mailContent, 'recipient@here.com');
```

Of course, what is interesting is the optional `$params` last argument, as it may contains :

- a `template` parameter (the body content of constructor is inserted in the template, replacing any %content% string
- a `bcc` parameter, to send the email to its recipient AND a bcc one (to be given as a string)
- a `testMode` parameter ; if set to True, the emails won't be sent to real recipients during `send` calls, but to test recipients (see below)
- a `testRecipients` parameter ; a PHP array of test emails to send emails to, if `testMode` equals True
- a `replyTo` parameter ; if set with an email string, it will insert a specific header in the email so that answer should be returned to another address
- a `toOverride` parameter ; if set, all emails are sent to this address (debug purposes ?)
- a `queue` parameter ; if set, a queue of the name provided will be created and call to `send` will push emails to the queue
- a `queueParams` parameter ; if using a queue, this is an associative array of `Store` object constructor parameters (root of queue subsystem and batch count)

The most interesting are the queue parameters, as it makes it possible to send emails either directly or through a queue, just with the same interface (MailSenderHelper class).

PHPUnit
-------

[](#phpunit)

To test with PHPUnit, point the -c configuration option to the /phpunit.xml configuration file.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity76

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~19 days

Recently: every ~5 days

Total

138

Last Release

755d ago

PHP version history (2 changes)1.0.0PHP &gt;= 7.0.0

1.0.21PHP &gt;= 7.2.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/2cb0c1d404c8ae72b0a731246130079c2f440d6ea079815ca8c153aa361b1f28?d=identicon)[nettools.ovh](/maintainers/nettools.ovh)

---

Top Contributors

[![net-tools](https://avatars.githubusercontent.com/u/6818724?v=4)](https://github.com/net-tools "net-tools (262 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/net-tools-mailing/health.svg)

```
[![Health](https://phpackages.com/badges/net-tools-mailing/health.svg)](https://phpackages.com/packages/net-tools-mailing)
```

###  Alternatives

[minishlink/web-push

Web Push library for PHP

1.9k12.0M53](/packages/minishlink-web-push)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

728272.9k20](/packages/civicrm-civicrm-core)[laravel-notification-channels/twilio

Provides Twilio notification channel for Laravel

2587.7M12](/packages/laravel-notification-channels-twilio)[spatie/url-signer

Generate a url with an expiration date and signature to prevent unauthorized access

4422.3M16](/packages/spatie-url-signer)[mattketmo/email-checker

Throwaway email detection library

2742.0M5](/packages/mattketmo-email-checker)[eduardokum/laravel-mail-auto-embed

Library for embed images in emails automatically

1702.0M5](/packages/eduardokum-laravel-mail-auto-embed)

PHPackages © 2026

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