PHP code example of monkeyscloud / monkeyslegion-mail
1. Go to this page and download the library: Download monkeyscloud/monkeyslegion-mail library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
monkeyscloud / monkeyslegion-mail example snippets
use MonkeysLegion\Mail\Mailer;
// Get mailer instance
$mailer = ML_CONTAINER->get(Mailer::class);
// Send immediately
$mailer->send(
'[email protected] ',
'Welcome to Our App',
'<h1>Welcome!</h1><p>Thanks for joining us.</p>',
'text/html'
);
// Queue for background processing (example.com',
'Welcome to Our App',
'<h1>Welcome!</h1><p>Thanks for joining us.</p>',
'text/html'
);
echo "Email queued with job ID: $jobId";
// Generate a new mailable class
php vendor/bin/ml make:mail WelcomeMail
// Use the generated class
use App\Mail\WelcomeMail;
$mail = new WelcomeMail();
$mail->setTo('[email protected] ')
->setViewData(['name' => 'John Doe'])
->send(); // or ->queue()
namespace App\Mail;
use MonkeysLegion\Mail\Mail\Mailable;
class OrderConfirmationMail extends Mailable
{
public function __construct(
private array $order,
private array $customer
) {
parent::__construct();
}
public function build(): self
{
return $this->view('emails.order-confirmation')
->subject('Order Confirmation #' . $this->order['id'])
->withData([
'order' => $this->order,
'customer' => $this->customer,
'total' => $this->order['total']
])
->attach('/path/to/invoice.pdf');
}
}
// Create and send
$order = ['id' => 12345, 'total' => 99.99];
$customer = ['name' => 'John Doe', 'email' => '[email protected] '];
$mail = new OrderConfirmationMail($order, $customer);
// Send immediately
$mail->setTo('[email protected] ')->send();
// Or queue for background processing
$jobId = $mail->setTo('[email protected] ')->queue();
// Configure dynamically
$mail->setTo('[email protected] ')
->setSubject('Custom Subject')
->onQueue('high-priority')
->send();
public function build(): self
{
// emails.welcome => root/resources/views/emails/welcome.ml.php
return $this->view('emails.welcome', [
'user' => $this->user,
'loginUrl' => 'https://app.com/login'
]);
}
class OrderConfirmationMail extends Mailable
{
// Queue configuration
protected ?string $queue = 'orders';
protected ?int $timeout = 120;
protected ?int $maxTries = 5;
// Content settings
protected string $contentType = 'text/html';
// Runtime methods also available
public function build(): self
{
return $this->view('emails.order')
->setTimeout(180) // Override timeout
->setMaxTries(3) // Override max tries
->setContentType('text/html') // Override content type
->addAttachment('/path/to/invoice.pdf');
}
}
public function build(): self
{
return $this->view('emails.newsletter')
->addAttachment('/path/to/file.pdf', 'Newsletter.pdf')
->setAttachments([
['path' => '/path/file1.pdf', 'name' => 'File1.pdf'],
['path' => '/path/file2.pdf', 'name' => 'File2.pdf']
]);
}
public function build(): self
{
return $this->view('emails.notification')
->when($this->user->isPremium(), function($mail) {
$mail->addAttachment('/path/to/premium-guide.pdf');
})
->unless($this->user->hasSeenWelcome(), function($mail) {
$mail->withData(['showWelcome' => true]);
});
}
// In your application
$jobId = $mailer->queue(
'[email protected] ',
'Newsletter',
$htmlContent,
'text/html',
[], // attachments
'newsletters' // specific queue
);
// Start worker (separate process)
// php vendor/monkeyscloud/monkeyslegion-mail/bin/ml-mail.php mail:work newsletters
'queue' => [
'worker' => [
'sleep' => 3, // Seconds between job checks
'max_tries' => 3, // Maximum retry attempts
'memory' => 128, // Memory limit (MB)
'timeout' => 60, // Job timeout (seconds)
],
],
use MonkeysLegion\Mail\Security\DkimSigner;
// Generate a new key pair
$keys = DkimSigner::generateKeys(2048);
echo "Private Key:\n" . $keys['private'] . "\n\n";
echo "Public Key:\n" . $keys['public'];
'smtp' => [
'host' => $_ENV['MAIL_HOST'] ?? 'smtp.mailtrap.io',
'port' => $_ENV['MAIL_PORT'] ?? 587,
'encryption' => $_ENV['MAIL_ENCRYPTION'] ?? 'tls', // tls / ssl / null
'username' => $_ENV['MAIL_USERNAME'] ?? '',
'password' => $_ENV['MAIL_PASSWORD'] ?? '',
'timeout' => $_ENV['MAIL_TIMEOUT'] ?? 30,
'from' => [
'address' => $_ENV['MAIL_FROM_ADDRESS'] ?? '[email protected] ',
'name' => $_ENV['MAIL_FROM_NAME'] ?? 'My App'
],
'dkim_private_key' => $_ENV['MAIL_DKIM_PRIVATE_KEY'] ?? '',
'dkim_selector' => $_ENV['MAIL_DKIM_SELECTOR'] ?? 'default',
'dkim_domain' => $_ENV['MAIL_DKIM_DOMAIN'] ?? '',
],
'mailgun' => [
'api_key' => $_ENV['MAILGUN_API_KEY'] ?? '',
'domain' => $_ENV['MAILGUN_DOMAIN'] ?? '',
'from' => [
'address' => $_ENV['MAIL_FROM_ADDRESS'] ?? '[email protected] ',
'name' => $_ENV['MAIL_FROM_NAME'] ?? 'Your App',
],
// Optional tracking options (used by addOptionalParameters)
'tracking' => [
'clicks' => filter_var($_ENV['MAILGUN_TRACK_CLICKS'] ?? true, FILTER_VALIDATE_BOOLEAN),
'opens' => filter_var($_ENV['MAILGUN_TRACK_OPENS'] ?? true, FILTER_VALIDATE_BOOLEAN),
],
// Optional delivery time in RFC2822 or ISO 8601 format
'delivery_time' => $_ENV['MAILGUN_DELIVERY_TIME'] ?? null,
// Optional array of tags (Mailgun supports up to 3 tags per message)
'tags' => explode(',', $_ENV['MAILGUN_TAGS'] ?? ''), // e.g. "welcome,new-user"
// Optional custom variables to
'null' => [
'from' => [
'address' => $_ENV['MAIL_FROM_ADDRESS'] ?? '[email protected] ',
'name' => $_ENV['MAIL_FROM_NAME'] ?? 'Your App'
]
]
'sendmail' => [
'path' => $_ENV['MAIL_SENDMAIL_PATH'] ?? '/usr/sbin/sendmail',
'from' => [
'address' => $_ENV['MAIL_FROM_ADDRESS'] ?? '[email protected] ',
'name' => $_ENV['MAIL_FROM_NAME'] ?? 'Your App'
],
// DKIM signing as SMTP configuration
],
return [
'key' => 'mail', // Unique identifier
'limit' => 100, // Max emails per window
'seconds' => 60, // Time window (seconds)
'storage_path' => '/mail', // Storage location
];
return [
'key' => 'mail', // Unique identifier
'limit' => 100, // Max emails per window
'seconds' => 60, // Time window (seconds)
'storage_path' => '/mail', // Storage location
];
use MonkeysLegion\Mail\RateLimiter\RateLimiter;
// Create rate limiter with config values
$rateLimiter = new RateLimiter('user_123', 100, 3600);
// Check remaining quota
$remaining = $rateLimiter->remaining(); // e.g., 85
// Get reset time
$resetTime = $rateLimiter->resetTime(); // seconds until reset
// Get configuration
$config = $rateLimiter->getConfig();
// Reset limit (admin function)
$rateLimiter->reset();
// Clean old records (scheduled task)
$stats = RateLimiter::cleanupAll('/tmp');
// cleanup-rate-limits.php
use MonkeysLegion\Mail\RateLimiter\RateLimiter;
$results = RateLimiter::cleanupAll('/tmp');
echo "Cleaned up " . $results['cleaned'] . " files\n";
// Successful send (Production)
[Log TimeStamp] app.INFO Email sent successfully {
"to": "[email protected] ",
"subject": "Welcome",
"duration_ms": 1250,
"driver": "SmtpTransport"
}
// DKIM signing (Development)
[Log TimeStamp] app.DEBUG DKIM signature generated {
"domain": "yourdomain.com",
"selector": "default",
"signature_length": 344,
"headers_signed": ["From", "To", "Subject", "Date", "Message-ID"]
}
// Queue processing (All modes)
[Log TimeStamp] app.INFO Job processed successfully {
"job_id": "job_64f8a2b1c3d4e",
"duration_ms": 890,
"memory_usage_mb": 15.2,
"queue": "emails"
}
// Rate limiting (Production)
[Log TimeStamp] app.WARNING Rate limit exceeded {
"key": "user_123",
"limit": 100,
"window": 3600,
"remaining_reset_time": 1845
}
// SMTP Debug (Development only)
[Log TimeStamp] app.DEBUG SMTP command sent {
"command": "MAIL FROM:<[email protected] >",
"response_code": 250,
"response": "2.1.0 Ok"
}
use MonkeysLegion\Mail\Logger\Logger;
$logger = ML_CONTAINER->get(Logger::class);
// Log custom events
$logger->log("Custom email campaign started", [
'campaign_id' => 'summer2024',
'recipient_count' => 1000,
'estimated_duration' => '5 minutes'
]);
// Switch drivers at runtime
$mailer->useSmtp(['host' => 'smtp.mailgun.org']);
$mailer->send($to, $subject, $content);
$mailer->useSendmail();
$mailer->send($to, $subject, $content);
$mailer->useNull();
$mailer->send($to, $subject, $content);
// Queue multiple emails efficiently
$recipients = ['[email protected] ', '[email protected] ', '[email protected] '];
foreach ($recipients as $recipient) {
$mail = new NewsletterMail($content);
$mail->setTo($recipient)
->onQueue('newsletters')
->queue();
}
// Process with dedicated worker
// php bin/ml-mail.php mail:work newsletters
bash
# Test email sending
php vendor/monkeyscloud/monkeyslegion-mail/bin/ml-mail.php mail:test [email protected]
bash
# Monitor queue status
php vendor/monkeyscloud/monkeyslegion-mail/bin/ml-mail.php mail:list
# Check for failed jobs
php vendor/monkeyscloud/monkeyslegion-mail/bin/ml-mail.php mail:failed
# Get queue statistics
redis-cli llen queue:emails # Pending jobs
redis-cli llen queue:failed # Failed jobs
bash
# Test email sending (bypasses queue)
php vendor/monkeyscloud/monkeyslegion-mail/bin/ml-mail.php mail:test [email protected]
bash
# Generate DKIM private and public key files in the specified directory
php vendor/bin/ml make:dkim-pkey <directory>
bash
# Test DKIM signing
php vendor/monkeyscloud/monkeyslegion-mail/bin/ml-mail.php mail:test [email protected]
bash
# Clean up old rate limit records every hour
0 * * * * php /path/to/cleanup-rate-limits.php