How do you configure Phalcon’s email services?

How do you configure Phalcon’s email services?

To configure Phalcon’s email services in minimal steps:

1. Install PHPMailer (or any other library)

Phalcon doesn’t have a built-in email service, so you’ll need to use an external library like PHPMailer. Install it via Composer:

Example

composer require phpmailer/phpmailer

2. Register the Email Service

In the DI container, register an email service using PHPMailer:

Example

<?php
use PHPMailer\PHPMailer\PHPMailer;
use Phalcon\Di\FactoryDefault;

$di = new FactoryDefault();

$di->setShared('mail', function () {
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Host       = 'smtp.example.com';  // Set SMTP server
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your_email@example.com';  // SMTP username
    $mail->Password   = 'your_password';    // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;  // Enable TLS encryption
    $mail->Port       = 587;

    return $mail;
});
?>

3. Send an Email

Use the registered service to send an email in your controller or service:

Example

<?php
$mail = $this->di->get('mail');
$mail->setFrom('from@example.com', 'Example');
$mail->addAddress('to@example.com', 'Recipient');
$mail->Subject = 'Test Email';
$mail->Body    = 'This is a test email.';
$mail->send();
?>

Related Questions & Topics