• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to send emails using CI 4

#1
I don't know this is silly question or not, but I did search for this in forum and google also but not getting any help. However, I came to know that PHPmailer and other libraries are coming in future, but for now, what is the code/how to do code that can send email to users.

I am developing simple sign in/sign up functionality using CI 4 where users needs to confirm their email address when they sign up. So I did try one or two codes but email is not sent to users. Here is code samples that I did try but not getting success. So can anyone please help me, how can I send emails to user.

Quote:Using simple PHP code :

PHP Code:
$to '[email protected]';
$subject 'the subject';
$message 'hello';
$headers 'From: [email protected]"\r\n" .
    
'Reply-To: [email protected]"\r\n" .
    
'X-Mailer: PHP/' phpversion();

if(
mail($to$subject$message$headers)) {
    echo 
'send';
}
else {
    echo 
'not send';    

Reply

#2
The PHP mail function nowadays only serves for internal testing.
Any SMTP server will reject emails from an unauthenticated account.

First register an account in gmail and then in the configuration of the Security section account, enable "Less secure app access"
Now every time you want to send an email you do it with that account, attached example below.

Anyway, using PHPMailer is the best option.

PHP Code:
if (!empty($_POST)) {

 
   $host 'ssl://smtp.gmail.com';
 
   $port '465';
 
   $user '[email protected]';
 
   $pass 'your-mail-password';
 
   $rcpt $user;
 
   $subj 'Web Form';
 
   $body '';
 
   $status false;

 
   foreach ($_POST as $i => $j) {
 
       $body .= strtoupper($i) . ': '$j "\r\n";
 
   }
 
   $body wordwrap(stripslashes($body), 70"\r\n");

 
   if (($fp = @fsockopen($host$port)) !== FALSE && substr(fgets($fp1024), 03) != '220') {
 
       $status 'CONNECTION FAIL';
 
   } else {
 
       fputs($fp"HELO $user\r\n");
 
       if (substr(fgets($fp1024), 03) != '250') {
 
           $status 'HELO FAIL';
 
       } else {
 
           fputs($fp"AUTH LOGIN\r\n");
 
           if (substr(fgets($fp1024), 03) != '334') {
 
               $status 'AUTH LOGIN FAIL';
 
           } else {
 
               fputs($fpbase64_encode($user) . "\r\n");
 
               if (substr(fgets($fp1024), 03) != '334') {
 
                   $status 'AUTH USER FAIL';
 
               } else {
 
                   fputs($fpbase64_encode($pass) . "\r\n");
 
                   if (substr(fgets($fp1024), 03) != '235') {
 
                       $status 'AUTH PASS FAIL';
 
                   } else {
 
                       fputs($fp"MAIL FROM: <$user>\r\n");
 
                       if (substr(fgets($fp1024), 03) != '250') {
 
                           $status 'MAIL FROM FAIL';
 
                       } else {
 
                           fputs($fp"RCPT TO: <$rcpt>\r\n");
 
                           if (substr(fgets($fp1024), 03) != '250') {
 
                               $status 'RCPT TO FAIL';
 
                           } else {
 
                               fputs($fp"DATA\r\n");
 
                               if (substr(fgets($fp1024), 03) != '354') {
 
                                    $status 'DATA FAIL';
 
                               } else {
 
                                   fputs($fp"To: $rcpt\r\nSubject: $subj\r\n\r\n$body\r\n.\r\n");
 
                                   if (substr(fgets($fp1024), 03) != '250') {
 
                                       $status 'BODY FAIL';
 
                                   } else {
 
                                       fputs($fp"QUIT \r\n");
 
                                       if (substr(fgets($fp1024), 03) != '221') {
 
                                           $status 'QUIT FAIL';
 
                                       } else {
 
                                           $status true;
 
                                       }
 
                                   }
 
                               }
 
                           }
 
                       }
 
                   }
 
               }
 
           }
 
       }
 
       fclose($fp);
 
   }

    if (
$status === true) {
 
       echo 'Your data was sent successfully.';
 
   } else {
 
       echo 'There was an error submitting your data (' $status ').';
 
   }


Reply

#3
There's a library in the works: https://forum.codeigniter.com/thread-73487.html
Reply

#4
Use this library https://github.com/PHPMailer/PHPMailer
Reply

#5
(06-07-2019, 08:21 AM)elephpantech Wrote: The PHP mail function nowadays only serves for internal testing.
Any SMTP server will reject emails from an unauthenticated account.

First register an account in gmail and then in the configuration of the Security section account, enable "Less secure app access"
Now every time you want to send an email you do it with that account, attached example below.

Anyway, using PHPMailer is the best option.

PHP Code:
if (!empty($_POST)) {

 
   $host 'ssl://smtp.gmail.com';
 
   $port '465';
 
   $user '[email protected]';
 
   $pass 'your-mail-password';
 
   $rcpt $user;
 
   $subj 'Web Form';
 
   $body '';
 
   $status false;

 
   foreach ($_POST as $i => $j) {
 
       $body .= strtoupper($i) . ': '$j "\r\n";
 
   }
 
   $body wordwrap(stripslashes($body), 70"\r\n");

 
   if (($fp = @fsockopen($host$port)) !== FALSE && substr(fgets($fp1024), 03) != '220') {
 
       $status 'CONNECTION FAIL';
 
   } else {
 
       fputs($fp"HELO $user\r\n");
 
       if (substr(fgets($fp1024), 03) != '250') {
 
           $status 'HELO FAIL';
 
       } else {
 
           fputs($fp"AUTH LOGIN\r\n");
 
           if (substr(fgets($fp1024), 03) != '334') {
 
               $status 'AUTH LOGIN FAIL';
 
           } else {
 
               fputs($fpbase64_encode($user) . "\r\n");
 
               if (substr(fgets($fp1024), 03) != '334') {
 
                   $status 'AUTH USER FAIL';
 
               } else {
 
                   fputs($fpbase64_encode($pass) . "\r\n");
 
                   if (substr(fgets($fp1024), 03) != '235') {
 
                       $status 'AUTH PASS FAIL';
 
                   } else {
 
                       fputs($fp"MAIL FROM: <$user>\r\n");
 
                       if (substr(fgets($fp1024), 03) != '250') {
 
                           $status 'MAIL FROM FAIL';
 
                       } else {
 
                           fputs($fp"RCPT TO: <$rcpt>\r\n");
 
                           if (substr(fgets($fp1024), 03) != '250') {
 
                               $status 'RCPT TO FAIL';
 
                           } else {
 
                               fputs($fp"DATA\r\n");
 
                               if (substr(fgets($fp1024), 03) != '354') {
 
                                    $status 'DATA FAIL';
 
                               } else {
 
                                   fputs($fp"To: $rcpt\r\nSubject: $subj\r\n\r\n$body\r\n.\r\n");
 
                                   if (substr(fgets($fp1024), 03) != '250') {
 
                                       $status 'BODY FAIL';
 
                                   } else {
 
                                       fputs($fp"QUIT \r\n");
 
                                       if (substr(fgets($fp1024), 03) != '221') {
 
                                           $status 'QUIT FAIL';
 
                                       } else {
 
                                           $status true;
 
                                       }
 
                                   }
 
                               }
 
                           }
 
                       }
 
                   }
 
               }
 
           }
 
       }
 
       fclose($fp);
 
   }

    if (
$status === true) {
 
       echo 'Your data was sent successfully.';
 
   } else {
 
       echo 'There was an error submitting your data (' $status ').';
 
   }


Hi elephpantech
I don't know how to integrate PHPMailer. can you please help
many thanks
Reply

#6
(06-25-2020, 07:14 AM)carlkyo Wrote: I don't know how to integrate PHPMailer. can you please help
many thanks

Have you tried using the Email Class that CI v4 provides? If you cannot get that to work it is unlikely you will find integrating PHPMailer to be easier.

That said, here are a couple of links to get you started.

Here are the installation directions for PHPMailer. Also on that page look for the A Simple Example section.  Use the example to create a simple controller for testing purposes. If you can get it to work and want to know how to make PHPMailer available as the "email" service then come back and ask a new question on this forum.
Reply

#7
PHPMailer integration should be pretty simple, you don't need any kind of package manager as you can just download the source and add the requisite use/include statements in your PHP code. I'd expect this to work:
  • Download the PHPMailer project from GitHub. Easiest way would be to clone https://github.com/PHPMailer/PHPMailer.git. Or you can download a ZIP of the source. Either way, at a bare minimum, you'll need the "language" and "src" folders. 
  • At the ROOT level of your project namespace, i.e. the directory that contains the app, public, writable, etc. directories, create a new directory called PHPMailer and put the PHPMailer code inside of it (e.g. <project_root>/PHPMailer/src/). Make sure to set file ownership/permissions appropriate to your web server.
  • Assuming you did that right, your CI code should be able to include PHPMailer code via namespace. In an example project called 'project' hosted by Apache, 
Code:
//Using a CI4 model for example
namespace App\Models;
use App\Models\SomeModel;
//PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
[color=#333333][size=small]use PHPMailer\PHPMailer\OAuth;[/size][/color]
[color=#333333][size=small]use PHPMailer\PHPMailer\Exception;[/size][/color]
use PHPMailer\PHPMailer\SMTP;

This should get you to the point where you can make a PHPMailer object wherever you include this code.
Reply

#8
i'm using PHPMailer because i've used it before and understand it.
First thing is how to instantiate class this is where i decided to put PHPMailer in a dev directory local host called ginbrookes:

ginbrookes
├── PHPMailer
├── admin
├── app
├── contributing
├── fontawesome
├── ginbrookes.zip
├── gulpfile.js
├── node_modules
├── package-lock.json
├── package.json
├── public
├── scss
├── system
└── writable


inside PHPMailer you have src with :

src
├── Exception.php
├── OAuth.php
├── PHPMailer.php
├── POP3.php
└── SMTP.php

inside Controllers i have a controller called "Sendmail.php" controller and i get access to PHPMailer via declaring this

<?php namespace App\Controllers;

use CodeIgniter\Controller;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\OAuth;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
use \App\Andy\CheckSpam;
use CodeIgniter\I18n\Time;



class Sendmail extends Controller


-------------------


the way i use it is for web surfers to get back to me via a form; the controller Sendmail.php is used to put together the elements from the form of
their name
their email
their message

the nitty gritty use of PHPmailer i use is as follows:

$mail = new PHPMailer();
//above is where you actually instantiate PHPMailer class and i can do this due to declaration above and location of PHPMailer directory
$mail->isSMTP();
$mail->Timeout = 20;
$mail->SMTPDebug = 0;
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//im using my 2 step gmail account
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "[email protected]";
//above im using my actual email account //Password to use for SMTP authentication
$mail->Password = "my 2 step pasword created via google 2 step ";
//Set who the message is to be sent from
$mail->setFrom('[email protected]', 'andy ');
$mail->addAddress('[email protected]', 'andy');
//Set the subject line
$mail->Subject = 'enquiry from my web site ';
$mail->Body = $this->totalMessage;

//above is collation i did in controller to make it easier
$this->totalMessage is a class member (variable) declared in sendmail class
$mail->send();



So basically i'm leveraging my gmail account to send web surfer info via a form to my yahoo email account.
You can use your web domain SMTP in my case i can't due to historical reasons and having cheap but reliable web hosting where i have a few webs all on add on domain basis. This is just an example how i use successfully on live webs that you might be able to cross reference with CI4 documentation and PHPMailer documentation


The onlt other point to mention is that if you look at PHPMailer.php and the other supporting class they have namespace :

namespace PHPMailer\PHPMailer;


So this might make sense when you look at my SendMail.php declaration for using PHPMailer
Reply

#9
Many many thanks captain-sensible.
I follow your instruction but it still failed.
I am appreciated if anyone can help, thanks again


Attached Files Thumbnail(s)
   
Reply

#10
it might be this your missing , i forgot about :

app/config/autoload.php

$psr4 = [
'Config' => APPPATH . 'Config',
APP_NAMESPACE => APPPATH, // For custom namespace
'App' => APPPATH, // To ensure filters, etc still found,

'Forms' => ROOTPATH.'forms',
'PHPMailer\\PHPMailer'=> ROOTPATH.'PHPMailer/src'


];


i added PHPMailer, (using two backspaces one to , basically this maps an actual namespace of PHPMailer\PHPMailer (look inside php files of mailer) to where the php files are, which is ROOTPATH.'PHPMailer/src'



One other tip the PHPMailer worked from my localhost using apache, so this doesn't need to be live to tets
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.