Google SMTP with Codeigniter

Google SMTP Configuration
A simple guide to setting up Google's SMTP for sending emails.
Step 1: Get an App Password
To use Google's SMTP, you must use a specific App Password instead of your regular Google password. You can generate one by following these steps:
- Go to your Google Account settings.
- Navigate to Security.
- Find 2-Step Verification and make sure it's turned On. This is a requirement.
-
Under the "Signing in to Google" section, find App Passwords. Or search it like below.
- Select a name for your app (e.g., "My Web App") or create one, and click "Generate".
- Google will provide a 16-character password.



Google SMTP Server Details
- Server: smtp.gmail.com
- Port (SSL): 465
- Security: (
TLS/STARTTLS/ssl) - Username: Your full Gmail address
- Password: The generated App Password
Let's try to check the STMP before going into Codeigniter framework
- Vist SMTP Test Tool
- Add details by filling the form
It will be something similar to this. 👇
SMTP Test
Test your SMTP server credentials by filling out this form.
We will use the Email library in CodeIgniter 4. This is one of the most used libraries in web application development. Sometimes we need to send an email related to account creation or purchasing a product, like sending an invoice or validating an account creation
If we are going to send an email using our local server, we need to configure SMTP.
We have app/Config/Email.php class. There, we have to configure our SMTP server. Once the configuration is completed, we have to load that email service into our controller.
- Let’s configure SMTP first.
- Let’s test the configuration by creating a controller class.
- Declare Routes
- Now you can try the email is working by visiting
your_baseurl/testmail
.
app>Config>Email.php
change the following variables
public $protocoal = “smtp”’;
public $SMTPHost = “smtp.gmail.com”;
public $SMTPUser = ‘your email address’;
public $SMTPPass = ‘App password generated’;
public $SMTPPort = 465;
public $SMTPTimeout = 60;
public $SMTPCrypto = ‘ssl’;
public $mailType = ‘html’
Use terminal
php spark make:controller TestMail
Now open the TestMail.php
class. And let's write our index function
public function index()
{
$from = ‘your email';
$to = 'email of the reciever';
$subject = 'Account Activation';
$message = 'Hi Kevin,
Please click the link below to activate your account.'
.'
Activate Account Now
Thanks,
Team CodeIgniter';
//instantiate email service
$email = \Config\Services::email();
$email->setFrom($from);
$email->setTo($to);
$email->setSubject($subject);
$email->setMessage($message);
//We can attach images too.
$filepath = 'public/assets/images/1.png';
$email->attach($filepath);
if($email->send())
{
echo 'Email sent successfully. Please Activate Your Account.';
}
else
{
//predefined function printDebugger
$data = $email->printDebugger(['headers']);
print_r($data);
}
}
Add the URI we just created.
$routes->get('testmail', 'TestMail::index');