PHPackages                             leuffen/template-mailer - 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. [Templating &amp; Views](/categories/templating)
4. /
5. leuffen/template-mailer

AbandonedArchivedLibrary[Templating &amp; Views](/categories/templating)

leuffen/template-mailer
=======================

Send mails including template engine

v2.5.4(7y ago)01.9kmitPHPPHP &gt;=5.5

Since Aug 1Pushed 7y ago3 watchersCompare

[ Source](https://github.com/dermatthes/template-mailer)[ Packagist](https://packagist.org/packages/leuffen/template-mailer)[ Docs](https://leuffen.de)[ RSS](/packages/leuffen-template-mailer/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (6)Dependencies (3)Versions (10)Used By (0)

Template-Mailer
===============

[](#template-mailer)

[![Downloads this Month](https://camo.githubusercontent.com/3818ceef9b8fff7128781bf745a7de9dbd960150c3bf633e955fbc96211f48b7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6c65756666656e2f74656d706c6174652d6d61696c65722e737667)](https://packagist.org/packages/leuffen/template-mailer)[![](https://camo.githubusercontent.com/8aef83c177ecc3b67793ebce1fd227c77f467ae1b994761ac6c201023ceba005/68747470733a2f2f7472617669732d63692e6f72672f6465726d6174746865732f74656d706c6174652d6d61696c65722e737667)](https://travis-ci.org/dermatthes/template-mailer)[![Latest Stable Version](https://camo.githubusercontent.com/874539cd0e45c916ec7c1e774f5bb7558fe478901ae81410a080dade6607b6be/68747470733a2f2f706f7365722e707567782e6f72672f6c65756666656e2f74656d706c6174652d6d61696c65722f762f737461626c65)](https://github.com/dermatthes/template-mailer/releases)[![Supports PHP 5.4+](https://raw.githubusercontent.com/xp-framework/web/master/static/php-5_4plus.png)](http://php.net/)[![Supports PHP 7.0+](https://raw.githubusercontent.com/xp-framework/web/master/static/php-7_0plus.png)](http://php.net/)

This project combines an powerfull but easy-to-use OOP interface to Multipart-Mime-Mails in conjunction with a easy to learn template-language for defining complete multipart-messages within one string. (Including subject, from, other headers, all kinds of message-parts).

Install
-------

[](#install)

Install using composer:

```
composer require leuffen/template-mailer

```

Basic Example
-------------

[](#basic-example)

> See directory `/doc/template/tpl/` for a bunch of working examples. You can life-test the examples with `/doc/template/SendTestMail.php` against your MailClient / MTA.

Define a template using text-template syntax

```
To: {= user.email};
From: support@some-company.com
Subject: Your order {= oder.id} on our site

Hello {= user.name},

you just ordered following items:

{for curItem in order.items}
{=@index1}: {=curItem.title|cutright:20} {=curItem.quantity} x {=curItem.price|currency}
{/for}

... do the same stuff in HTML

```

*Notice: To display the html-content by default it's important, to put the text/html content to the end of the mail*

Load the template and send the mail:

```
$parser = new MailTemplateParser();
$parser->loadTemplate($template);
$parser->send ($orderData);
```

That's it

### Adding MailParts to a template

[](#adding-mailparts-to-a-template)

Use the `apply()` method to not just send the mail but return the `MailBody`:

```
$parser = new MailTemplateParser();
$parser->loadTemplate ($template);
$mail = $parser->apply($orderData);
```

Add an attachment using the `FileAttachment` helper class:

```
$mail->addPart(new FileAttachment("path/to/image.jpg"));
```

or the manual way:

```
$mail->addPart(
    $_part = new MailBody(
        chunk_split(
            base64_encode(
                file_get_contents($fileName)
                ),
                75
            ),
        mime_content_type($fileName),
        "UTF-8",
        "base64"
    )
);
$_part->setContentDispositionFileName(basename($fileName));
```

send the mail:

```
$mail->send();
```

That's it.

Programmatic multipart example
------------------------------

[](#programmatic-multipart-example)

You can use template-mailer to send multipart-mail without any templating directly from your code:

```
$mailBody = new MailBody ("to@address.de", "Some subject", "from@me.de");
$mailBody->addPart (new MailPart ("Some Text Content", "text/plain"));
$mailBody->addPart (new MailPart ("Some Html Part", "text/html"));
$mailBody->send();
```

Using the Template Engine
-------------------------

[](#using-the-template-engine)

For standard purpose you should use the MailTemplateParser to generate your Mail. But template-mailer can also be used like an OOP Mail Frontend. You'll find mor Information about that topic in the next section.

### Security enhancements when using Templates

[](#security-enhancements-when-using-templates)

- **Auto Escaping**: TemplateParser will escape values according to your content-type. Values in text/html mailParts will be htmlspecialchars()'d
- **Mail injection**: Values in the header-section will be automaticly trimmed to 255 bytes and LineBreaks are converted to spaces
- **Transparent Encoding**: The templating-engine will set and encode any content in the best available transfer-encoding
- **UTF-8 by default**: Both, templates and values are expected in corret UTF-8 formatting. By default outgoing mails will be UTF-8 formated as well - unless you change the Charset: - Header. In this case template-mail will do tranparent conversion for you.

### Defining Templates

[](#defining-templates)

Template-Mail uses Text-Template () Syntax to define your templates.

Template consist of two sections. The *header-section*...

```
To: Some User
Subject: Some fancy mail subject

```

... followed by **one empty line**, and the *body-section*...

```

  ..content goes here..

..more mail-parts..

```

... where you define each part of your mail between `` and ``.

You don't have to take care about boundaries, additional headers nor correct escaping.

When defining mailPart you can use the attributes defined below to fit your needs:

AttributeDescriptionAllowed valuescontentTypetext/plain, text/html, application/pdf, ...contentDispositionattachment, inlinecontentTransferEncodingDefault: 8Bit8Bit, quoted-printable, base64charsetDefault: UTF-8utf-8, iso-8895-1, ...fileNameUsed with contentDispositon="attachment": The filename to display in attachementstokenidUsed to reference attached files. If you name it `somefile` you can reference it ``skipEncodingIf skipEncoding="no" is present, Text-Template will do no own encoding to the contentsYES, NO### The MailBody Content-Type

[](#the-mailbody-content-type)

One word to the content-type of the container-mail:

- **`multipart/mixed`**: Default, if more than one mailPart isset

    - All Parts are shown in order of occurence
    - Attachments possible
- **`multipart/alternative`**: Use this if you want to display only one part (HTML or TEXt) with inline Attachements

    - Last part has highest precedence
    - Attachments will not be displayed
- **`multipart/related`**: Use this if you want to embed attachements into the mail

    - First part has highest precedence
    - Inline-Attachments will not be displayed if they are displayed inside html-code.

By default, Template-Mailer will set the content-type in de header of the container-mail to `multipart/mixed`, which allows multiple attachments.

But it will display all attachments.

You can set it to use `multipart/alternative` by adding the Header

```
..in Header..
Content-Type: multipart/alternative

```

### Debugging the context

[](#debugging-the-context)

To see the structure of the data passed to the template just add

```
{= __CONTEXT__ | raw }

```

to your template. It will output the structure of the context.

### Accessing the TextTemplate Parser

[](#accessing-the-texttemplate-parser)

To access and configure the TextTemplate Parser use the `MailTemplateParser::getTextTemplateParser()` method.

Example:

```
$mailTemplateParser->getTextTemplateParser()->addFilter("price", function ($input) { return number_format($input) });

```

### Changing the Deliveryagent to an non local SMTP Server

[](#changing-the-deliveryagent-to-an-non-local-smtp-server)

To change the DeliveryAgent, it must be set in the MailKernel, via the static function SetMailDeliveryAgent The SmtpDeliveryAgent uses the class PHPMailer to send an SMTP Message to the chosen Server

Example:

```
$mailDeliveryAgent = new SmtpDeliveryAgent("localhost");
MailKernel::SetMailDeliveryAgent($mailDeliveryAgent);

```

About
-----

[](#about)

Template-Mailer was written by Matthias Leuffen

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 62.5% 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 ~2 days

Total

9

Last Release

2851d ago

PHP version history (2 changes)v2.0.1PHP &gt;=5.6

2.5PHP &gt;=5.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/878a384d056698a2400e4b7c8858db05a6caebb2c560e67151be36d46d58def0?d=identicon)[dermatthes](/maintainers/dermatthes)

---

Top Contributors

[![dermatthes](https://avatars.githubusercontent.com/u/13380559?v=4)](https://github.com/dermatthes "dermatthes (15 commits)")[![michaelkaiser02](https://avatars.githubusercontent.com/u/62561211?v=4)](https://github.com/michaelkaiser02 "michaelkaiser02 (5 commits)")[![AlGoore](https://avatars.githubusercontent.com/u/4050047?v=4)](https://github.com/AlGoore "AlGoore (3 commits)")[![aligit93](https://avatars.githubusercontent.com/u/14941072?v=4)](https://github.com/aligit93 "aligit93 (1 commits)")

---

Tags

mailtemplate

### Embed Badge

![Health badge](/badges/leuffen-template-mailer/health.svg)

```
[![Health](https://phpackages.com/badges/leuffen-template-mailer/health.svg)](https://phpackages.com/packages/leuffen-template-mailer)
```

###  Alternatives

[phpoffice/phpword

PHPWord - A pure PHP library for reading and writing word processing documents (OOXML, ODF, RTF, HTML, PDF)

7.5k34.7M181](/packages/phpoffice-phpword)[rize/uri-template

PHP URI Template (RFC 6570) supports both expansion &amp; extraction

420137.3M46](/packages/rize-uri-template)[text/template

Simple and secure string-template-engine (Twig-like syntax) with nested if/elseif/else, loops, filters. Simple OOP api: Just one class doing the job (2-lines of code). Fast and secure: No code-generation, no eval'ed() code. Extensible by callbacks. Fully tested. Rich examples included.

38201.1k10](/packages/text-template)[dansmaculotte/laravel-mail-template

A mail template driver to send emails with

353.0k](/packages/dansmaculotte-laravel-mail-template)[larablocks/pigeon

A more flexible email message builder for Laravel 5 including chained methods, reusable message configurations, and message layout and template view management.

143.7k](/packages/larablocks-pigeon)[muratbsts/mail-template

This package is a easy to use mail template collection for Laravel 5.x.

191.3k](/packages/muratbsts-mail-template)

PHPackages © 2026

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