CHNAGE_GMAILAPI_IMPLEMENTED

This commit is contained in:
velz 2024-09-04 17:30:53 +05:30
parent d83c8fcd6f
commit 90e85d93f1
8 changed files with 381 additions and 3 deletions

View File

@ -278,12 +278,16 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->get("copy_insurer_templete/(:any)", "MasterController::copyInsurerTemplete/$1");
$routes->get("get_single_excel_template/(:any)", "MasterController::getSingleExcelTemplate/$1");
$routes->get("dublicate_template/(:any)", "MasterController::duplicateTemplate/$1");
$routes->get("test_mail", "MasterController::testGmailAPI");
$routes->post("test_mail", "MasterController::testGmailAPI");
});
$routes->cli('cli/processjob', 'JobWorker::processJob');
$routes->cli('cli/processjobs', 'JobWorker::processJobs');
$routes->cli('cli/enrollment_status', 'JobWorker::enrollment_status');
$routes->get("processjob", "JobWorker::processJob");
$routes->cli('cli/new_gmail_token', 'MasterController::generateNewGmailAPIToken');
$routes->cli('cli/send_mail_cli', 'MasterController::testGmailAPIViaCLI');

View File

@ -5,6 +5,7 @@ namespace Config;
use CodeIgniter\Config\BaseService;
use App\Libraries\Slug;
use App\Libraries\MyLogger;
use App\Libraries\GmailAPI;
use App\Libraries\DataServiceSqlite;
use App\Controllers\Home;
@ -60,5 +61,14 @@ class Services extends BaseService
return new DataServiceSqlite();
}
public static function gmailapi($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('gmailapi');
}
return new GmailAPI();
}
}

View File

@ -10,6 +10,7 @@ use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Files\File;
use App\Helpers\DepositHelper;
use App\Helpers\MailHelper;
use App\Models\UserModel;
use App\Models\ClientModel;
@ -1440,4 +1441,59 @@ class MasterController extends AdminController
]);
}
}
public function generateNewGmailAPIToken()
{
$gmailapi = \Config\Services::gmailapi();
$gmailapi->generateNewToken();
}
//testing a sample mail from front end
public function testGmailAPI()
{
if ($this->request->getMethod() == 'post') {
$gmailapi = \Config\Services::gmailapi();
$to = $this->request->getPost('to');
$subject = $this->request->getPost('subject');
$mail_content = $this->request->getPost('content');
/*****CHOOSE ANY ONE AT A TIME, COMMENT ANOTHER ONE******/
/*****CALLING DIRECLT USING LIB******/
// $res = $gmailapi->sendMessage($to, $subject, $mail_content, 'info@nhanceindia.in', 'info@nhanceindia.in', $cc = [], $bcc = []);
// if($res['status'])
// {
// return $this->respond(['status' => 'success','code' => 200,'data' => $res],200);
// }
// else
// {
// $this->respond(['status' => 'failed','code' => 500,'data' => $res],200);
// }
/*****CALLING DIRECLT USING LIB******/
/*****CALLING VIA MAIL HELPER******/
$res = MailHelper::send_email(['mail' => $to, 'subject' => $subject, 'message' => $mail_content]);
return $this->respond(['status' => 'success','code' => 200,'data' => $res],200);
/*****CALLING VIA MAIL HELPER******/
}
$this->loadLayout('mail_test');
}
//testing a sample mail from cli
public function testGmailAPIViaCLI()
{
$gmailapi = \Config\Services::gmailapi();
$res = MailHelper::send_email(['mail' => 'velmurugan.s@venbainfotech.com', 'subject' => 'Mail Via CLI', 'message' => 'This is sample mail sent via CLI mode']);
print_r($res);
}
}

View File

@ -14,7 +14,7 @@ use App\Models\JobModel;
class MailHelper
{
public static function send_email($params)
public static function send_email_smtp($params)
{
// print_r($params);die;
@ -63,7 +63,7 @@ class MailHelper
}
}
public static function bulk_mail(array $mails = [])
public static function bulk_mail_smtp(array $mails = [])
{
// print_r();die;
$model = new JobModel();
@ -82,5 +82,69 @@ class MailHelper
}
}
//using GmailAPI
public static function send_email($params)
{
// print_r($params);die;
$myLogger = \Config\Services::mylogger();
$gmailapi = \Config\Services::gmailapi();
$emaill = $params['mail'];
$subject = $params['subject'];
$message = $params['message'];
if (isset($params['bcc'])) {
$bcc = $params['bcc'];
}else{
$bcc = [];
}
if (isset($params['cc'])) {
$cc = $params['cc'];
}else{
$cc = [];
}
try {
$res = $gmailapi->sendMessage($emaill, $subject, $message, 'info@nhanceindia.in', 'info@nhanceindia.in', $cc, $bcc);
if($res['status'])
{
return json_encode(['status' => 'success','code' => 200, 'message'=>('Email Sent Successfully...'.$emaill),'data' => $res,],200);
}
else
{
$myLogger->logme('error', "mail sent failed - $emaill");
return json_encode(['status' => 'failed','code' => 404,'message'=>( 'Email Sent Failed...' . $emaill ),'data' => $res ],404);
}
} catch (Exception $e) {
$msg = $e->getMessage();
$myLogger->logme('error', "mail sent failed - $msg");
return json_encode(['status' => 'failed','code' => 500,'data' => $msg],500);
}
}
public static function bulk_mail(array $mails = [])
{
// print_r();die;
$model = new JobModel();
$start = microtime(true);
$runtime= 0;
try {
foreach ( $mails as $index=>$mail) {
$runtime = microtime(true) - $start;
$send_mail = self::send_email($mail);
}
return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
} catch (\Throwable $th) {
return json_encode(['status' => 'failed','code' => 500],500);
}
}
}
?>

180
app/Libraries/GmailAPI.php Normal file
View File

@ -0,0 +1,180 @@
<?php
namespace App\Libraries;
use Google\Client;
use Google\Service\Gmail;
use Google\Service\Gmail\Message;
use App\Models\SettingsModel;
use CodeIgniter\CLI\CLI;
class GmailAPI
{
protected $client;
protected $service;
protected $tokenField = 'email_token';
protected $myLogger = '';
protected $authField = 'gmail_api_oauth_credentials';
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
$this->client = new Client();
$this->client->setApplicationName('Nhance GmailAPI');
$this->client->setScopes([
'https://www.googleapis.com/auth/gmail.addons.current.message.readonly',
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/gmail.labels',
'https://www.googleapis.com/auth/gmail.send'
]);
$this->setAuthConfig();
//die();
$this->client->setAccessType('offline');
$this->client->setPrompt('select_account consent');
if (php_sapi_name() !== 'cli' || (uri_string() == 'cli/send_mail_cli' || uri_string() == 'cli/processjob') )
{
$this->setTokenFromDB(); // Call only if not in CLI
}
$this->service = new Gmail($this->client);
}
protected function setAuthConfig()
{
$settingsModel = new SettingsModel();
$credentials = $settingsModel->where('id', 1)->first();
if (!$credentials) {
$this->myLogger->logme('error','OAuth credentials for GmailAPI not found in database.');
throw new \Exception('OAuth credentials for GmailAPI not found in database.');
}
// print_r($credentials[$this->authField]);//die();
// $accessToken = $credentials[$this->authField];
$this->client->setAuthConfig(json_decode($credentials[$this->authField],true));
// if ($this->client->isAccessTokenExpired()) {
// if ($this->client->getRefreshToken()) {
// $this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
// $this->storeTokenToDB($this->client->getAccessToken());
// } else {
// $this->myLogger->logme('error', 'Access token expired and no refresh token available.');
// throw new \Exception('Access token expired and no refresh token available.');
// }
// }
}
protected function setTokenFromDB()
{
$settingsModel = new SettingsModel();
$token = $settingsModel->where('id', 1)->first();
// dd(is_array($token) && is_null($token[$this->tokenField]));
if (is_array($token) && is_null($token[$this->tokenField])) {
$this->myLogger->logme('error','Email Token not found in database.');
throw new \Exception('Email Token not found in database.');
}
$accessToken = json_decode($token[$this->tokenField], true);
$this->client->setAccessToken($accessToken);
if ($this->client->isAccessTokenExpired()) {
if ($this->client->getRefreshToken()) {
$this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
$this->storeTokenToDB($this->client->getAccessToken());
} else {
$this->myLogger->logme('error', 'Access token expired and no refresh token available.');
throw new \Exception('Access token expired and no refresh token available.');
}
}
}
protected function storeTokenToDB($token)
{
$settingsModel = new SettingsModel();
$token = json_encode($token);
// $settingsModel->update(['id' => $this->tokenField], ['value' => json_encode($token)]);
$settingsModel->where('id', 1)->set([$this->tokenField => $token])->update();
}
public function createMessage($to, $subject, $htmlContent, $from, $replyTo, $cc = [], $bcc = [])
{
$boundary = uniqid(rand(), true);
$rawMessageString = "From: $from\r\n";
$rawMessageString .= "To: $to\r\n";
$rawMessageString .= "Reply-To: $replyTo\r\n";
if (!empty($cc)) {
$rawMessageString .= "Cc: " . implode(',', $cc) . "\r\n";
}
if (!empty($bcc)) {
$rawMessageString .= "Bcc: " . implode(',', $bcc) . "\r\n";
}
$rawMessageString .= "Subject: $subject\r\n";
$rawMessageString .= "MIME-Version: 1.0\r\n";
$rawMessageString .= "Content-Type: multipart/alternative; boundary=\"$boundary\"\r\n\r\n";
$rawMessageString .= "--$boundary\r\n";
$rawMessageString .= "Content-Type: text/html; charset=UTF-8\r\n";
$rawMessageString .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$rawMessageString .= $htmlContent . "\r\n";
$rawMessageString .= "--$boundary--";
$rawMessage = base64_encode($rawMessageString);
$rawMessage = str_replace(['+', '/', '='], ['-', '_', ''], $rawMessage);
$message = new Message();
$message->setRaw($rawMessage);
return $message;
}
public function sendMessage($to, $subject, $htmlContent, $from, $replyTo, $cc = [], $bcc = [])
{
try {
$message = $this->createMessage($to, $subject, $htmlContent, $from, $replyTo, $cc, $bcc);
$res = $this->service->users_messages->send('me', $message);
return array('status' => true, 'data' => $res);
} catch (\Exception $e) {
$err_msg = 'An error occurred while sending the mail: ' . $e->getMessage();
$this->myLogger->logme('error', $err_msg);
// throw new \Exception('An error occurred while sending the mail: ' . $e->getMessage());
return array('status' => false, 'data' =>$e->getMessage());
}
}
public function generateNewToken()
{
// dd('called');
if (!is_cli()) {
throw new \RuntimeException('This method can only be accessed via the command line.');
}
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
$authUrl = $this->client->createAuthUrl();
CLI::write('Open the following link in your browser');
CLI::write("\n");
CLI::write($authUrl);
// printf ("Open the following link in your browser:\n%s\n", $authUrl);
CLI::write('Enter verification code: ');
// print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
$accessToken = $this->client->fetchAccessTokenWithAuthCode($authCode);
if (array_key_exists('error', $accessToken)) {
$this->myLogger->logme('error', 'Error in getting access token from authCode' . join(', ', $accessToken));
throw new \Exception(join(', ', $accessToken));
}
$this->storeTokenToDB($accessToken);
$this->myLogger->logme('error', 'New token generated and stored in the database.');
print 'New token generated and stored in the database.';
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class SettingsModel extends Model
{
protected $table = 'settings';
protected $primaryKey = 'id';
protected $allowedFields = [
'mail_host',
'mail_port',
'mail_username',
'mail_password',
'email_token',
'created_by',
'updated_by'
];
}

44
app/Views/mail_test.php Normal file
View File

@ -0,0 +1,44 @@
<div class="container mt-2">
<h2>Send Test Mail Using Gmail API</h2>
<form id="mailForm">
<div class="form-group">
<label for="to">To:</label>
<input type="email" class="form-control" id="to" name="to" value="velmurugan.s@venbainfotech.com" required>
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="text" class="form-control" id="subject" name="subject" value="Gmail API Test - . <?php echo date('Y-m-d h:i:s');?>" required>
</div>
<div class="form-group">
<label for="content">Content:</label>
<textarea class="form-control" id="content" name="content" rows="5" required><H1>Gmail API Test </H1><a target="_blank" href="<?php echo base_url('util/test_mail')?>">Click me</a>
</textarea>
</div>
<button type="submit" class="btn btn-primary">Send Mail</button>
</form>
<div id="responseMessage" class="mt-3"></div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function() {
$('#mailForm').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '<?= base_url('util/test_mail') ?>', // Replace with your controller method URL
type: 'POST',
data: $(this).serialize(),
success: function(response) {
$('#responseMessage').html('<div class="alert alert-success">' + JSON.stringify(response.data) + '</div>');
},
error: function(xhr, status, error) {
$('#responseMessage').html('<div class="alert alert-danger">Error: ' + xhr.responseText + '</div>');
}
});
});
});
</script>

View File

@ -728,7 +728,7 @@
var old_data = data.old;
const tableBody = document.getElementById(tableID);
// $(("#".tableID)).empty();
$("#restable tbody").empty()
$("#restable tbody").empty();
$('#oldrestable tbody').empty();
const existingRowCount = tableBody.rows.length;
for(i = 0; i < data.length; i++)