• Stars
    star
    466
  • Rank 94,105 (Top 2 %)
  • Language
    PHP
  • License
    Other
  • Created over 10 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A handy library for creating and sending emails in PHP

Nette Mail: Sending E-mails

Downloads this Month Tests Coverage Status Latest Stable Version License

Introduction

Are you going to send emails such as newsletters or order confirmations? Nette Framework provides the necessary tools with a very nice API.

Documentation can be found on the website.

Support Me

Do you like Nette Mail? Are you looking forward to the new features?

Buy me a coffee

Thank you!

Installation

composer require nette/mail

It requires PHP version 8.0 and supports PHP up to 8.2.

Creating Emails

Email is a Nette\Mail\Message object:

$mail = new Nette\Mail\Message;
$mail->setFrom('John <[email protected]>')
	->addTo('[email protected]')
	->addTo('[email protected]')
	->setSubject('Order Confirmation')
	->setBody("Hello, Your order has been accepted.");

All parameters must be encoded in UTF-8.

In addition to specifying recipients with the addTo() method, you can also specify the recipient of copy with addCc(), or the recipient of blind copy with addBcc(). All these methods, including setFrom(), accepts addressee in three ways:

$mail->setFrom('[email protected]');
$mail->setFrom('[email protected]', 'John Doe');
$mail->setFrom('John Doe <[email protected]>');

The body of an email written in HTML is passed using the setHtmlBody() method:

$mail->setHtmlBody('<p>Hello,</p><p>Your order has been accepted.</p>');

You don't have to create a text alternative, Nette will generate it automatically for you. And if the email does not have a subject set, it will be taken from the <title> element.

Images can also be extremely easily inserted into the HTML body of an email. Just pass the path where the images are physically located as the second parameter, and Nette will automatically include them in the email:

// automatically adds /path/to/images/background.gif to the email
$mail->setHtmlBody(
	'<b>Hello</b> <img src="background.gif">',
	'/path/to/images'
);

The image embedding algorithm supports the following patterns: <img src=...>, <body background=...>, url(...) inside the HTML attribute style and special syntax [[...]].

Can sending emails be even easier?

Emails are like postcards. Never send passwords or other credentials via email.

Attachments

You can, of course, attach attachments to email. Use the addAttachment(string $file, string $content = null, string $contentType = null).

// inserts the file /path/to/example.zip into the email under the name example.zip
$mail->addAttachment('/path/to/example.zip');

// inserts the file /path/to/example.zip into the email under the name info.zip
$mail->addAttachment('info.zip', file_get_contents('/path/to/example.zip'));

// attaches new example.txt file contents "Hello John!"
$mail->addAttachment('example.txt', 'Hello John!');

Templates

If you send HTML emails, it's a great idea to write them in the Latte template system. How to do it?

$latte = new Latte\Engine;
$params = [
	'orderId' => 123,
];

$mail = new Nette\Mail\Message;
$mail->setFrom('John <[email protected]>')
	->addTo('[email protected]')
	->setHtmlBody(
		$latte->renderToString('email.latte', $params),
		'/path/to/images'
	);

File email.latte:

<html>
<head>
	<meta charset="utf-8">
	<title>Order Confirmation</title>
	<style>
	body {
		background: url("background.png")
	}
	</style>
</head>
<body>
	<p>Hello,</p>

	<p>Your order number {$orderId} has been accepted.</p>
</body>
</html>

Nette automatically inserts all images, sets the subject according to the <title> element, and generates text alternative for HTML body.

Sending Emails

Mailer is class responsible for sending emails. It implements the Nette\Mail\Mailer interface and several ready-made mailers are available which we will introduce.

SendmailMailer

The default mailer is SendmailMailer which uses PHP function mail(). Example of use:

$mailer = new Nette\Mail\SendmailMailer;
$mailer->send($mail);

If you want to set returnPath and the server still overwrites it, use $mailer->commandArgs = '[email protected]'.

SmtpMailer

To send mail via the SMTP server, use SmtpMailer.

$mailer = new Nette\Mail\SmtpMailer([
	'host' => 'smtp.gmail.com',
	'username' => '[email protected]',
	'password' => '*****',
	'secure' => 'ssl',
]);
$mailer->send($mail);

If you do not specify host, the value from php.ini will be used. The following additional keys can be used in the options:

  • port - if not set, the default 25 or 465 for ssl will be used
  • context - allows you to set SSL context options for connection
  • timeout - timeout for SMTP connection
  • persistent - use persistent connection
  • clientHost - client designation

FallbackMailer

It does not send email but sends them through a set of mailers. If one mailer fails, it repeats the attempt at the next one. If the last one fails, it starts again from the first one.

$mailer = new Nette\Mail\FallbackMailer([
	$smtpMailer,
	$backupSmtpMailer,
	$sendmailMailer
]);
$mailer->send($mail);

Other parameters in the constructor include the number of repeat and waiting time in miliseconds.

DKIM

DKIM (DomainKeys Identified Mail) is a trustworthy email technology that also helps detect spoofed messages. The sent message is signed with the private key of the sender's domain and this signature is stored in the email header. The recipient's server compares this signature with the public key stored in the domain's DNS records. By matching the signature, it is shown that the email actually originated from the sender's domain and that the message was not modified during the transmission of the message.

$options = [
	'domain' => 'nette.org',
	'selector' => 'dkim',
	'privateKey' => file_get_contents('../dkim/dkim.key'),
	'passPhrase' => '****',
];

$mailer = new Nette\Mail\SendmailMailer; // or SmtpMailer
$mailer->setSigner(new Nette\Mail\DkimSigner($options));
$mailer->send($mail);

More Repositories

1

php-generator

🐘 Generates neat PHP code for you. Supports new PHP 8.3 features.
PHP
2,109
star
2

utils

🛠 Lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.
PHP
1,988
star
3

tracy

😎 Tracy: the addictive tool to ease debugging PHP code for cool developers. Friendly design, logging, profiler, advanced features like debugging AJAX calls or CLI support. You will love it.
PHP
1,755
star
4

nette

👪 METAPACKAGE for Nette Framework components
PHP
1,531
star
5

latte

☕ Latte: the safest & truly intuitive templates for PHP. Engine for those who want the most secure PHP sites.
PHP
1,137
star
6

finder

🔍 Finder: find files and directories with an intuitive API.
932
star
7

neon

🍸 Encodes and decodes NEON file format.
PHP
904
star
8

schema

📐 Validating data structures against a given Schema.
PHP
896
star
9

robot-loader

🍀 RobotLoader: high performance and comfortable autoloader that will search and autoload classes within your application.
PHP
871
star
10

di

💎 Flexible, compiled and full-featured Dependency Injection Container with perfectly usable autowiring and support for all new PHP 8 features.
PHP
869
star
11

bootstrap

🅱 The simple way to configure and bootstrap your Nette application.
PHP
666
star
12

database

💾 A database layer with a familiar PDO-like API but much more powerful. Building queries, advanced joins, drivers for MySQL, PostgreSQL, SQLite, MS SQL Server and Oracle.
PHP
507
star
13

forms

📝 Generating, validating and processing secure forms in PHP. Handy API, fully customizable, server & client side validation and mature design.
PHP
495
star
14

tester

Tester: enjoyable unit testing in PHP with code coverage reporter. 🍏🍏🍎🍏
PHP
460
star
15

http

🌐 Abstraction for HTTP request, response and session. Provides careful data sanitization and utility for URL and cookies manipulation.
PHP
456
star
16

caching

⏱ Caching library with easy-to-use API and many cache backends.
PHP
411
star
17

application

🏆 A full-stack component-based MVC kernel for PHP that helps you write powerful and modern web applications. Write less, have cleaner code and your work will bring you joy.
PHP
407
star
18

security

🔑 Provides authentication, authorization and a role-based access control management via ACL (Access Control List)
PHP
354
star
19

component-model

⚛ Component model foundation for Nette.
PHP
266
star
20

routing

Nette Routing: two-ways URL conversion
PHP
236
star
21

tokenizer

[DISCONTINUED] Source code tokenizer
PHP
141
star
22

sandbox

141
star
23

docs

📖 The Nette documentation
116
star
24

safe-stream

SafeStream: atomic and safe manipulation with files via native PHP functions.
PHP
115
star
25

web-project

Standard Web Project: a simple skeleton application using the Nette
Latte
106
star
26

reflection

[DISCONTINUED] Docblock annotations parser and common reflection classes
PHP
92
star
27

examples

🎓 Examples demonstrating the Nette Framework.
88
star
28

code-checker

✅ A simple tool to check source code against a set of Nette coding standards.
PHP
84
star
29

web-addons.nette.org

[DISCONTINUED] Website https://addons.nette.org source code.
PHP
55
star
30

coding-standard

Nette Coding Standard code checker & fixer
PHP
39
star
31

command-line

⌨ Command line options and arguments parser.
PHP
36
star
32

type-fixer

🆙 A tool to automatically update typehints in your code.
PHP
29
star
33

resources

Client-side resources for Nette Framework.
23
star
34

latte-tools

Twig & HTML to Latte converters
PHP
22
star
35

grunt-nette-tester

Grunt plugin for Nette Tester
JavaScript
20
star
36

middleware

PHP
20
star
37

deprecated

[DISCONTINUED] APIs and features removed from Nette Framework
PHP
19
star
38

safe

🛡 PHP functions smarten up to throw exceptions instead of returning false or triggering errors.
PHP
17
star
39

nette-minified

[DISCONTINUED] Minified version of Nette Framework.
PHP
16
star
40

tutorial-todo

[DISCONTINUED] Tutorial for simple task manager.
PHP
10
star
41

union

[READ-ONLY] Subtree union of Nette repositories
PHP
7
star
42

assistant

PHP
3
star
43

.github

1
star