nette/mail
Composer 安装命令:
composer require nette/mail
包简介
📧 Nette Mail: A handy library for creating and sending emails in PHP.
README 文档
README
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?
Thank you!
Installation
composer require nette/mail
It requires PHP version 8.2 and supports PHP up to 8.5.
Creating Emails
Email is a Nette\Mail\Message object:
$mail = new Nette\Mail\Message; $mail->setFrom('John <john@example.com>') ->addTo('peter@example.com') ->addTo('jack@example.com') ->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('john.doe@example.com'); $mail->setFrom('john.doe@example.com', 'John Doe'); $mail->setFrom('John Doe <john.doe@example.com>');
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 <john@example.com>') ->addTo('jack@example.com') ->setHtmlBody( $latte->renderToString('/path/to/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.
CSS Inlining
Email clients often ignore <style> tags, so CSS needs to be applied as inline style attributes. The CssInliner does this automatically and also adds HTML attributes (bgcolor, width, align) for Outlook.
$html = (new Nette\Mail\CssInliner) ->addCss('p { margin: 0; } a { color: #a0704e; }') ->inline($html);
Rules from <style> tags in the HTML are extracted and inlined too. The <style> tags are preserved so that @media queries keep working. CSS nesting is supported.
Requires PHP 8.4+ (ext-dom).
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 = '-fmy@email.com'.
SmtpMailer
To send mail via the SMTP server, use SmtpMailer.
$mailer = new Nette\Mail\SmtpMailer( host: 'smtp.gmail.com', username: 'franta@gmail.com', password: '*****', encryption: Nette\Mail\SmtpMailer::EncryptionSSL, ); $mailer->send($mail);
The following additional parameters can be passed to the constructor:
port- if not set, the default 25 or 465 forsslwill be usedtimeout- timeout for SMTP connectionpersistent- use persistent connectionclientHost- client designationstreamOptions- allows you to set SSL context options for connection
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 milliseconds.
Interceptor
For debugging or as a safety net on staging, Interceptor wraps any mailer. When redirectTo is set, every outgoing message is cloned and the headers To, Cc, Bcc, Disposition-Notification-To and X-Confirm-Reading-To are replaced with the fixed address; the original values are preserved as X-Original-* headers and the original Message instance is left untouched.
$mailer = new Nette\Mail\Interceptor( mailer: $smtpMailer, redirectTo: 'dev@example.com', subjectPrefix: '[debug]', ); $mailer->send($mail);
The $onSent callable list is invoked after each send() with the original Message (before any redirect rewrite) and either null on success or a Throwable on failure:
$mailer->onSent[] = function (Nette\Mail\Interceptor $sender, Nette\Mail\Message $mail, ?Throwable $error): void { // audit log, metrics, … };
In a Nette application, the Interceptor is wired automatically when mail.redirect or mail.debugger: true is set. In debug mode, a Tracy Bar panel listing sent emails is attached as well.
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.
$signer = new Nette\Mail\DkimSigner( domain: 'nette.org', selector: 'dkim', privateKey: file_get_contents('../dkim/dkim.key'), passPhrase: '****', ); $mailer = new Nette\Mail\SendmailMailer; // or SmtpMailer $mailer->setSigner($signer); $mailer->send($mail);
nette/mail 适用场景与选型建议
nette/mail 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10.15M 次下载、GitHub Stars 达 492, 最近一次更新时间为 2014 年 03 月 20 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「mail」 「mailer」 「mime」 「nette」 「smtp」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 nette/mail 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 nette/mail 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 nette/mail 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A PHP class providing static methods for reading, writing, copying, moving, and deleting files and directories, MIME type detection, image size detection, and file permission management
Parse a generic mail stream, and convert it to a SwiftMailer Message
Send messages via Mailgun and synchronise with Mailgun Events API.
Courier offers a convenient and painless solution for creating emails tailored for your Kirby website.
Creates new sare mail transport for laravel applications
Zend Framework 1 Mime package
统计信息
- 总下载量: 10.15M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 540
- 点击次数: 29
- 依赖项目数: 269
- 推荐数: 1
其他信息
- 授权协议: BSD-3-Clause
- 更新时间: 2014-03-20