You can send an email using Gmail SMTP In CodeIgniter 4. For sending an email, you have to configure the email settings in your application. If you are sending email through the SMTP then there are two protocols that are TLS and SSL. Both protocols work on different ports. In this post, I will show you how you send email using Gmail in CodeIgniter 4. In CodeIgniter, there are different preferences available for determining how your email messages are sent. You can either set them manually or automatically. You can manage the preferences stored in the project config file. Here, I will start with a new project in CodeIgniter 4.
Prerequisites
To make a working email configuration in CodeIgniter 4, you need to have a project. But, for creating a new project, you must have the below configuration.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create a Project to Send Email Using Gmail
For creating the project, I will be using the composer. Hence, hit the below command to start the installation.
composer create-project codeigniter4/appstarter ci4-email
The above command will start the installation inside the specified directory.
Once the project has been created, you need to do the email configuration.
How to Implement jQuery Datatable in CodeIgniter 4
Configure Project Environment in CodeIgniter 4
Open the created project in VS Code editor and in the root of project, you will have the env file. So, firstly, you need to rename it to .env. Then search for the Environment configuration there.
You have to change the environment to development from the production.
#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------
CI_ENVIRONMENT = development
That’s it for the environment configuration. In the next step, you will have to configure the email settings.
Email Configuration in CodeIgniter 4
Inside the project folder, look for the app/Config/Email.php file. Here, you have to set the email settings. You have to do the below configuration.
public $SMTPHost = 'smtp.googlemail.com';
public $SMTPUser = 'YOUR_EMAIL';
public $SMTPPass = 'EMAIL_ACCOUNT_PASSWORD';
public $SMTPPort = 465/587;
public $SMTPTimeout = 60;
public $SMTPCrypto = 'ssl/tls';
public $mailType = 'html';
For the Gmail password, you have to generate it inside the Google account settings. It will accept the app password. So, don’t use the real password of your Gmail account.
The configuration will look like this-
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
/**
* @var string
*/
public $fromEmail;
/**
* @var string
*/
public $fromName;
/**
* @var string
*/
public $recipients;
/**
* The "user agent"
*
* @var string
*/
public $userAgent = 'CodeIgniter';
/**
* The mail sending protocol: mail, sendmail, smtp
*
* @var string
*/
public $protocol = 'smtp';
/**
* The server path to Sendmail.
*
* @var string
*/
public $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Address
*
* @var string
*/
public $SMTPHost = 'smtp.googlemail.com';
/**
* SMTP Username
*
* @var string
*/
public $SMTPUser = 'YOUR_EMAIL';
/**
* SMTP Password
*
* @var string
*/
public $SMTPPass = 'EMAIL_ACCOUNT_PASSWORD';
/**
* SMTP Port
*
* @var integer
*/
public $SMTPPort = 465;
/**
* SMTP Timeout (in seconds)
*
* @var integer
*/
public $SMTPTimeout = 60;
/**
* Enable persistent SMTP connections
*
* @var boolean
*/
public $SMTPKeepAlive = false;
/**
* SMTP Encryption. Either tls or ssl
*
* @var string
*/
public $SMTPCrypto = 'ssl';
/**
* Enable word-wrap
*
* @var boolean
*/
public $wordWrap = true;
/**
* Character count to wrap at
*
* @var integer
*/
public $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*
* @var string
*/
public $mailType = 'html';
/**
* Character set (utf-8, iso-8859-1, etc.)
*
* @var string
*/
public $charset = 'UTF-8';
/**
* Whether to validate the email address
*
* @var boolean
*/
public $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*
* @var integer
*/
public $priority = 3;
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*
* @var string
*/
public $CRLF = "\r\n";
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*
* @var string
*/
public $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*
* @var boolean
*/
public $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*
* @var integer
*/
public $BCCBatchSize = 200;
/**
* Enable notify message from server
*
* @var boolean
*/
public $DSN = false;
}
Now, that’s it for the configuration. Let’s create a controller to implement the functionality to send email using Gmail.
Generate Fake Data in CodeIgniter 4 Using Seeder and Faker
Create a Controller to Send Email Using Gmail
For creating the controller, I will be using the spark command. Hence, hit the below command in the terminal.
php spark make:controller EmailController
It will create a controller with the name EmailController.php.
After creating the controller, you will have to implement the functionality to send email using gmail.
How to Remove index.php From URL in CodeIgniter 4
Add Functionality to Send Email Using Gmail
CodeIgniter provides the email services to be load before sending the email. Hence, you need to load the below services inside the controller. You may create the constructor or even load it especially inside the function.
\Config\Services::email()
We will send an email through the form. So, we will pass the data dynamically. Firstly, add the below functions in the controller.
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
class EmailController extends BaseController
{
/**
* function to load email view
* @param NA
* @return NA
*/
public function index()
{
return view('email');
}
/**
* Function to send email
* @param NA
* @return $msg to view
*/
public function sendMail() {
$inputs = $this->validate([
'email' => 'required|valid_email',
'subject' => 'required|min_length[5]',
'message' => 'required|min_length[10]'
]);
if (!$inputs) {
return view('email', [
'validation' => $this->validator
]);
}
$to = $this->request->getVar('email');
$subject = $this->request->getVar('subject');
$message = $this->request->getVar('message');
$email = \Config\Services::email();
$email->setTo($to);
$email->setFrom('admin@programmingfields.com', 'Contact Email');
$email->setSubject($subject);
$email->setMessage($message);
if ($email->send()) {
$response = 'Email successfully sent';
}
else
{
$data = $email->printDebugger(['headers']);
$response ='Email send failed';
}
return redirect()->to( base_url('email') )->with('message', $response);
}
}
In the above source code, we have two functions.
- The first function is just for loading a view. The view will contain a basic form for sending the email.
- In the second function, firstly, I have created a validation rule. Once the form will be validated then it will trigger the next iteration.
- Next, I have read the data which are coming through the form. Then loaded the email services for applying email configuration in this function.
- Now, set the form data to a separate variable. Lastly, called the send() function using the email service object.
- If the email is sent, it will return the success message to the view with the session flash data.
Upload Multiple Image with Validation in Codeigniter 4
Create Routes in CodeIgniter 4
After creating the functions, let’s add routes. You can find the Routes.php inside the app/Config folder.
$routes->get('email', 'EmailController::index');
$routes->post('email', 'EmailController::sendMail');
After creating the routes, you need to create the view from where the data will be coming.
Create a View to Send Email Using Gmail
Navigate to the app/Views folder and create a view named email.php. After creating the view, let’s put the below code inside it.
<!doctype html>
<html lang="en">
<head>
<title>Send Email in CodeIgniter 4</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid py-4">
<?php $validation = \Config\Services::validation(); ?>
<h3 class="display-6 text-center font-weight-bold">Send Email in CodeIgniter 4 Using Gmail SMTP </h3>
<div class="row pt-4 border border-bottom-0">
<div class="col-xl-6 col-lg-6 col-md-8 col-sm-12 m-auto">
<form action="<?= base_url('email') ?>" method="POST">
<?= csrf_field() ?>
<?= (session()->getFlashdata('message')) ?
'<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>'
.session()->getFlashdata('message').
'</div>': '' ?>
<div class="card shadow">
<div class="card-header">
<h4 class="card-title font-weight-bold">Send Email </h4>
</div>
<div class="card-body">
<div class="form-group">
<label>To <span class="text-danger">*</span></label>
<input type="email" name="email" class="form-control <?= $validation->getError('email') ? 'is-invalid': ''?>" placeholder="Email Recipient"/>
<?= $validation->getError('name') ? '<div class="invalid-feedback">'.$validation->getError("email") .'</div>': ''?>
</div>
<div class="form-group">
<label>Subject <span class="text-danger">*</span></label>
<input type="text" name="subject" class="form-control <?= $validation->getError('subject') ? 'is-invalid': ''?>" placeholder="Subject"/>
<?= $validation->getError('subject') ? '<div class="invalid-feedback">'.$validation->getError("subject") .'</div>': ''?>
</div>
<div class="form-group">
<label>Message <span class="text-danger">*</span> </label>
<textarea name="message" class="form-control <?= $validation->getError('message') ? 'is-invalid': ''?>" placeholder="Your Message"></textarea>
<?= $validation->getError('message') ? '<div class="invalid-feedback">'.$validation->getError("message") .'</div>': ''?>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success">Send Email </button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
In the above snippet, I have created a form with three inputs are as follow.
- Email Recipient
- Subject
- Message
In the form, I have displayed the validation error message using the validation() service. Also, dsiplayed a flash data message that will come after the email is sent.
How to Upload Image and File in Codeigniter 4 with Validation
Check Result of Email
So, check the result in the browser by navigating the the route. The route is- http://localhost:8080/email
.
Now, try sending email without filling up the required details. In the response, you will get the validation error message as showing below.
Lastly, try filling up details correctly and hit the button to trigger email.
Here, email has been received in other mailbox.
Conclusion
We have configured the Gmail SMTP in CodeIgniter 4 for sending emails. After the successful configuration, we are able to send email using Gmail SMTP. We have seen the SMTP protocol as TLS and SSL. If you use SSL then the email will be transmitted through a secured channel. It is a good and secure way to send email using SSL. The ports for both protocols are different. The delivery of email totally depends on the mail host. So, I hope this post will helpful for you.
Roger says
just test the send method but appears this error: ‘Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method’
Umesh Rana says
Have you configured email settings correctly?
Senz Aura says
I love your tutorial, please make for JWT/API Keys/ Shield auth with code igniter too
Umesh Rana says
Thanks for your feedback. I will share that very soon.