Welcome Guest, Not a member yet? Register   Sign In
email example for CI4
#5

(This post was last modified: 07-17-2020, 07:12 AM by mlurie.)

Tom,

I am also relatively new to CodeIgniter.  In the past I have always used PHPMailer too, but CI4's mail class is just as good and easier to implement within the framework. 

The first thing you should do is set your mail server's configuration in App\Config\Email.php using $protocol, $SMTPHost, $SMTPUser, $SMTPPass, $SMTPPort, and $SMTPCrypto.

Alternatively, you can simply add the following to your .env file:

Code:
#--------------------------------------------------------------------
# E-Mail
#--------------------------------------------------------------------

email.protocol = 'smtp'
email.SMTPHost = 'mail.mailserver.com'
email.SMTPUser = '[email protected]'
email.SMTPPass = 'password'
email.SMTPPort = '465'
email.SMTPCrypto = 'ssl'

Use email.SMTPPort = '587' and email.SMTPCrypto = 'tls' if your mail server uses TLS instead of SSL.

Here is a simple code snippet that takes POST data from a mail form and sends it as an e-mail to the specified recipient:

PHP Code:
//Expecting $_POST['Name', 'Email', 'Phone', 'Message']
public function send() {

    
helper('form');

    
//Check for POST data
    
if($this->request->getMethod() == 'post') {
        
        
//Define validation rules
        
$rules = [
            
//POST data validation rules here
        
];

        
//Validate POST data
        
if(!$this->validate($rules)) {
            
$data['validation'] = $this->validator;
            return 
view('view_name'$data);  //Specify view name of mail form
        
} else {
            
            
//Send mail form data
            
$email Services::email();
            
$email->setFrom($this->request->getPost('Email'), $this->request->getPost('Name'));
            
$email->setTo('[email protected]');
            
$email->setSubject('Your Subject Here...');

            
$message  'Name: ' $this->request->getPost('Name') . "\n";
            
$message .= 'E-Mail: ' $this->request->getPost('Email') . "\n";
            
$message .= 'Phone: ' $this->request->getPost('Phone') . "\n";
            
$message .= 'Message: ' $this->request->getPost('Message') . "\n";
            
$email->setMessage($message);

            if(
$email->send()) {
                
//Handle success here...
            


            
//Output errors for debugging if necessary
            //echo $email->printDebugger();
            //exit;
        
}
    }
    
//Handle any errors here...


I hope this helps you get started.
Reply


Messages In This Thread
email example for CI4 - by carlkyo - 06-24-2020, 05:25 AM
RE: email example for CI4 - by Chroma - 06-29-2020, 09:04 AM
RE: email example for CI4 - by ivantcholakov - 06-29-2020, 02:04 PM
RE: email example for CI4 - by carlkyo - 07-02-2020, 02:48 AM
RE: email example for CI4 - by mlurie - 07-17-2020, 06:46 AM



Theme © iAndrew 2016 - Forum software by © MyBB