Phpmailer works on a project created without a framework but does not work with a project created with Codeigniter

Asked

Viewed 64 times

0

Initially, I created a project without any kind of php framework where I needed to use Phpmailer to send an email.

It turns out that right now, I’m redoing the project using the Codeigniter framework where I need to submit a.

Seeing that I was unable to use the native "mail()" php function, I went back to Phpmailer where I searched for a version that fits the framework. Version used: https://github.com/ivantcholakov/codeigniter-phpmailer

When editing the code with the respective information to my server, it gives me the following error:

2019-04-08 15:48:36 SERVER -> CLIENT: 220-ws2.multisnet.net ESMTP Exim 4.91 #1 Mon, 08 Apr 2019 16:48:19 +0100 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.
2019-04-08 15:48:36 CLIENT -> SERVER: EHLO localhost
2019-04-08 15:48:36 SERVER -> CLIENT: 250-ws2.multisnet.net Hello 233.254.115.89.rev.vodafone.pt [89.115.254.233]250-SIZE 52428800250-8BITMIME250-PIPELINING250-AUTH PLAIN LOGIN250-STARTTLS250 HELP
2019-04-08 15:48:36 CLIENT -> SERVER: STARTTLS
2019-04-08 15:48:36 SERVER -> CLIENT: 220 TLS go ahead
SMTP Error: Could not connect to SMTP host.
2019-04-08 15:48:37 CLIENT -> SERVER: QUIT
2019-04-08 15:48:37 
2019-04-08 15:48:37 
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

It turns out that by doing the same but without the framework, php Mailer works at 100%.

Does anyone know what it might be? I’ve confirmed all data 1000x

Code without framework :

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
           try {
             $servidoremail = file('../public/servidoremail.txt',FILE_IGNORE_NEW_LINES);
             $sname= $servidoremail['0'];
             $suser= $servidoremail['1'];
             $spass= $servidoremail['2'];
             $sport= $servidoremail['3'];
    //Server settings
             $mail->SMTPOptions = array(
              'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
              )
            );
              //$mail->SMTPDebug = 2;                                 // Enable verbose debug output
              $mail->isSMTP();                                      // Set mailer to use SMTP
              $mail->Host =  $sname;  // Specify main and backup SMTP servers
              $mail->SMTPAuth = true;                               // Enable SMTP authentication
              $mail->Username = $suser;                 // SMTP username
              $mail->Password =  $spass;                           // SMTP password
              $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
              $mail->Port = $sport ;                                    // TCP port to connect to

              //Recipients
              $mail->setFrom('[email protected]', 'Samsic App');
              $mail->addAddress($u->__get('email'));     // Add a recipient


              //Attachments
              //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
              //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

              //Content
              $mail->isHTML(true);                                  // Set email format to HTML
              $mail->Subject = 'Verificar email. Samsic App';
              $mail->Body    = '<a href="http://localhost/projetoobjetosTOTAL/public/pages/verify.php?vkey='.$vkey.'"> Clique para confirmar o seu registo na Samsic App </a>' ;
              $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

              $mail->send();

Codeigniter Email config :

<?php defined('BASEPATH') OR exit('No direct script access allowed.');

$config['useragent']        = 'PHPMailer';              // Mail engine switcher: 'CodeIgniter' or 'PHPMailer'
$config['protocol']         = 'smtp';                   // 'mail', 'sendmail', or 'smtp'
$config['mailpath']         = '/usr/sbin/sendmail';
$config['smtp_host']        = '********';
$config['smtp_auth']        = TRUE;
$config['_smtp_auth']        = TRUE;                      // Whether to use SMTP authentication, boolean TRUE/FALSE. If this option is omited or if it is NULL, then SMTP authentication is used when both $config['smtp_user'] and $config['smtp_pass'] are non-empty strings.
$config['smtp_user']        = '*********';
$config['smtp_pass']        = '*********';
$config['smtp_port']        = **;
$config['smtp_timeout']     = 30;                       // (in seconds)
$config['smtp_crypto']      = 'tls';                       // '' or 'tls' or 'ssl'
$config['smtp_debug']       = 2;                        // PHPMailer's SMTP debug info level: 0 = off, 1 = commands, 2 = commands and data, 3 = as 2 plus connection status, 4 = low level data output.
$config['debug_output']     = '';                       // PHPMailer's SMTP debug output: 'html', 'echo', 'error_log' or user defined function with parameter $str and $level. NULL or '' means 'echo' on CLI, 'html' otherwise.
$config['smtp_auto_tls']    = false;                     // Whether to enable TLS encryption automatically if a server supports it, even if `smtp_crypto` is not set to 'tls'.
$config['smtp_conn_options'] = array();                 // SMTP connection options, an array passed to the function stream_context_create() when connecting via SMTP.
$config['wordwrap']         = true;
$config['wrapchars']        = 76;
$config['mailtype']         = 'html';                   // 'text' or 'html'
$config['charset']          = null;                     // 'UTF-8', 'ISO-8859-15', ...; NULL (preferable) means config_item('charset'), i.e. the character set of the site.
$config['validate']         = true;
$config['priority']         = 3;                        // 1, 2, 3, 4, 5; on PHPMailer useragent NULL is a possible option, it means that X-priority header is not set at all, see https://github.com/PHPMailer/PHPMailer/issues/449
$config['crlf']             = "\n";                     // "\r\n" or "\n" or "\r"
$config['newline']          = "\n";                     // "\r\n" or "\n" or "\r"
$config['bcc_batch_mode']   = false;
$config['bcc_batch_size']   = 200;
$config['encoding']         = '8bit';                   // The body encoding. For CodeIgniter: '8bit' or '7bit'. For PHPMailer: '8bit', '7bit', 'binary', 'base64', or 'quoted-printable'.

// DKIM Signing
// See https://yomotherboard.com/how-to-setup-email-server-dkim-keys/
// See http://stackoverflow.com/questions/24463425/send-mail-in-phpmailer-using-dkim-keys
// See https://github.com/PHPMailer/PHPMailer/blob/v5.2.14/test/phpmailerTest.php#L1708
$config['dkim_domain']      = '';                       // DKIM signing domain name, for exmple 'example.com'.
$config['dkim_private']     = '';                       // DKIM private key, set as a file path.
$config['dkim_private_string'] = '';                    // DKIM private key, set directly from a string.
$config['dkim_selector']    = '';                       // DKIM selector.
$config['dkim_passphrase']  = '';                       // DKIM passphrase, used if your key is encrypted.
$config['dkim_identity']    = '';                       // DKIM Identity, usually the email address used as the source of the email.

Codeigniter send mail function:

$this->load->library('email');
$this->email->from('****');
$this->email->to('***');
$this->email->message('Olá');
if($this->email->send()){
    echo "enviado";

 }else{
    echo "não enviado";
       }

2 answers

0

You can elaborate that way:

In your controller, that would then be the form Submit or the submission itself:

function enviar_email(){ 

    # Envia e-mail com cópia para o e-mail do usuário
    $this->load->library('php_mailer');
    $email = new PHPMailer();
    $email->CharSet = 'utf-8';
    $email->SetFrom("[email protected]", "Nome 1");
    $email->AddAddress("[email protected]", "Nome 1");
    $email->Subject = "Inscrição de Curso - ".date("d/m/Y H:i");
    $email->MsgHTML("
        <b> INSCRIÇÃO EFETUADA</b><br>
        <br>
        <b> Nome:</b> ".$dados['nome']."<br>
        <b> E-mail:</b> ".$dados['email']."<br>
        <b> Telefone:</b> ".$dados['telefone']."<br>
        <b> Observações:</b> ".$dados['observacoes']."<br>
        <br>
        Solicitação enviada em ".date('d/m/Y H:i')."
        ");
    $email->send();

}

In this case, $dados['campo'] I’m using coming from $this->input->post('campo');

In the folder libraries, you then have the folder php_mailer, with two files:

class.phpmailer.php - https://pastebin.com/eCnc4hM1
class.smtp.php - https://pastebin.com/57sNZw4h

This way it will work perfectly.

0

I do it this way, it never went wrong, sending by gmail, just have to take the security of the email otherwise gmail blocks sending. In case I use the codeigniter’s own email library, pass the configs and just call and send the email.

 $config = array(
                'protocol' => 'smtp',
                'smtp_host' => 'ssl://smtp.googlemail.com',
                'smtp_port' => 465,
                'smtp_user' => '[email protected]',
                'smtp_pass' => 'senhaemail',
                'mailtype' => 'html',
                'set_crlf' => "\r\n",
                'charset' => 'utf-8',
                'wordwrap' => TRUE
            );
            $this->load->library('email');

            $this->email->initialize($config);

            $this->email->set_newline("\r\n");
            $this->email->from('[email protected], 'Nome de contato');
            $this->email->to([email protected]);
            $this->email->subject("TITULO DO EMAIL");
            $this->email->message("DIGITE AQUI O EMAIL, PODE UTILIZAR HTML");
            if($this->email->send()){
                return true;
            }else{
                return false;
            }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.