How to send HTML email with Codeigniter4

Sending SMTP HTML mail from CI4 is a simplified process. Codeigniter 4 provides multiple configuration options
to send email with charset, wordwrap, protocol option, encryptions, mail with attachments and many more.

Let us see how to send a simple html mail with Codeigniter 4.

The basic configuration settings for this can be found at app/Config/Email.php file.

Set the below configurations for SMTP in app/Config/Email.php.

public $protocol = 'smtp';
public $SMTPHost = <YOUR_SMTP_HOST>;  (As given by your smtp provider)
public $SMTPUser = <SMTP USERNAME>;
public $SMTPPass = <SMTP PASSWORD>;
public $SMTPPort = 587;
public $mailType = 'html';

Alternatively you can set the configurations at runtime as below.

$email = \Config\Services::email();
$config['protocol'] = 'smtp';
$config['SMTPHost']  = <YOUR_SMTP_HOST>'; 
$config['SMTPUser']  = <SMTP USERNAME>; 
$config['SMTPPass']  = <SMTP PASSWORD>;
$config['SMTPPort']  = 587; 
$config['mailType'] = 'html';

$email->initialize($config);

This will initialize the settings at runtime.

Create the html file at Views\welcome.html.
This ensures the html file is separately maintained and modified as needed.
Then you can refer this html file when sending mail as below.

$useremail = <YOUR_RECEIVER_EMAIL>;
$email->setFrom(<SENDER_EMAIL_ID>, <SENDER_NAME>);
$email->setTo($useremail);
$email->setSubject('Welcome To dvxlab.com');
$message =  view('App\Views\welcome.html');
$email->setMessage($message);
$email->send();

The statement $email->send returns a boolean valule and notifies if message was mailed successfully.

Leave a Reply