How to send email using template in codeigniter?

by aniya.jaskolski , in category: PHP Frameworks , 8 months ago

How to send email using template in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 8 months ago

@aniya.jaskolski 

To send an email using a template in CodeIgniter, you can follow these steps:

  1. Make sure you have configured the email settings in the config file. Open application/config/email.php and set up the necessary parameters like SMTP host, username, password, etc.
  2. Create a new controller method or modify an existing one to send the email. For example, let's create a new method called send_email in a controller called EmailController.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public function send_email()
{
    $this->load->library('email');
    
    // Set the email parameters
    $this->email->from('[email protected]', 'Your Name');
    $this->email->to('[email protected]');
    $this->email->subject('Email Subject');
    
    // Set the email template
    $email_template = $this->load->view('email/template', '', TRUE); // Load the template file
    
    $this->email->message($email_template); // Set the template as the email message
    
    // Send the email
    if ($this->email->send()) {
        echo 'Email sent successfully.';
    } else {
        echo 'Error sending email: ' . $this->email->print_debugger();
    }
}


  1. Create an email template view file. In the example above, we're using a template file called 'email/template'. Create a new view file called template.php in the application/views/email/ directory (you can change the directory as per your preference) with the required HTML structure and placeholders.


Here's an example of the template.php file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<html>
<head>
    <title>Email Template</title>
</head>
<body>
    <h1>Hello, {{recipient_name}}!</h1>
    <p>This is a sample email template.</p>
    <p>Thank you for using our service.</p>
</body>
</html>


In the template file, you can use placeholders like {{recipient_name}} that will be replaced dynamically with data when sending the email.

  1. Customize the email content and template placeholders as per your requirements.
  2. Finally, access the send_email method in your browser or through a route to send the email.


Note: Make sure you have set the correct email configuration in the config file and you have loaded the email library before sending the email.