2

I'm trying to connect to my Office365 account and send out an email in Codeigniter 3:

$config['protocol'] = 'smtp';
$config['smtp_host'] = 'smtp.office365.com';
$config['smtp_user'] = '****';
$config['smtp_pass'] = '****';
$config['smtp_port'] = '587';
$config['smtp_timeout'] = '60';
$config['smtp_crypto'] = 'tls';
$config['mailtype'] = 'html';
$this->email->initialize($config);

$this->email->from('****', '****');
$this->email->to('****');

$this->email->subject('Email Test');
$this->email->message('Testing the email class.');

$this->email->send(FALSE);

$this->email->print_debugger();

This code works fine on my local server (wamp), but not on my production server (Debian), that's why I suspect some settings on the server need to be altered. All I get is this:

A PHP Error was encountered

Severity: Warning

Message: fsockopen(): unable to connect to smtp.office365.com:587 (Connection timed out)

Filename: libraries/Email.php

Line Number: 1949

I also tried sending mail with Phpmailer class and I got the same result; works on my local machine, not on production server.

Codeigniter class uses function fsockopen to connect to the mail server, but I can't find out the solution, since I don't know much about server configuration.

Any suggestion would be appreciated!

rannt
  • 75
  • 1
  • 4
  • 12
  • visit-http://stackoverflow.com/questions/6310573/gmail-smtp-not-working-in-my-hosting-using-codeigniter-framework – Sagar Naliyapara Jun 29 '15 at 12:51
  • visit-http://stackoverflow.com/questions/1555145/sending-email-with-gmail-smtp-with-codeigniter-email-library – Sagar Naliyapara Jun 29 '15 at 12:52
  • Thank you for a quick reply. I tested the ports with the script I found in one of those answers. I managed to unblock ports 587 and 465 on my server firewall. Now if I try to send the mail with Phpmailer library, everything works fine! However, I'm still unable to send out email within Codeigniter. I get this error now: Message: stream_socket_enable_crypto(): SSL: crypto enabling timeout – rannt Jun 29 '15 at 13:26
  • http://stackoverflow.com/questions/14978459/warning-stream-socket-enable-crypto-this-stream-does-not-support-ssl-crypto – Sagar Naliyapara Jun 29 '15 at 13:30
  • http://php.net/manual/en/function.stream-socket-enable-crypto.php – Sagar Naliyapara Jun 29 '15 at 13:30
  • http://stackoverflow.com/questions/18931607/phpmailer-this-stream-does-not-support-ssl-crypto – Sagar Naliyapara Jun 29 '15 at 13:30
  • I found both of the questions (and answers) you are referring to, but if I check my "phpinfo", it says I already have openssl enabled. Also I'm running my server on Debian, and if I'm not mistaking, dll libraries are for Windows base environments? – rannt Jun 29 '15 at 13:40
  • As I said, on my local server everything works fine. The problem is on production server, which is based on Debian. I did manage to open the ports on server firewall and I'm now able to send out mails with Phpmailer library on my production server. But the problem in Codeigniter is still there. Anyone? Thank you! – rannt Jun 29 '15 at 18:29
  • Anyone? Any help would be really appreciated. Thank you! – rannt Jun 30 '15 at 06:52
  • sending mail using local host?? – Abdulla Nilam Jun 30 '15 at 07:01
  • you can set your details in config/email.php file – Sagar Naliyapara Jun 30 '15 at 07:24
  • The problem is not in the Codeigniter configuration, it has to be somehow related to server settings. I can easily send out and email using Phpmailer script with the same settings I'm using in Codeigniter, where an error occurs! – rannt Jun 30 '15 at 07:48
  • Did you ever solve this? Same issue here – jonboy Jun 19 '17 at 09:55
  • I solved it by switching from Office365 smtp servers to Sendgrid smtp servers. Which was a good idea anyway, because of the detailed statistics available. – rannt Jun 21 '17 at 12:05

5 Answers5

8

Here is what has worked for me in the past:

<?php 
$config['smtp_crypto'] = 'tls'; 
$config['protocol'] = 'smtp'; 
$config['smtp_host'] = 'smtp.office365.com';
$config['smtp_user'] = 'USER@EMAIL.COM'; 
$config['smtp_pass'] = 'password'; 
$config['smtp_port'] = '587'; 
$config['charset']='utf-8'; // Default should be utf-8 (this should be a text field) 
$config['newline']="\r\n"; //"\r\n" or "\n" or "\r". DEFAULT should be "\r\n" 
$config['crlf'] = "\r\n"; //"\r\n" or "\n" or "\r" DEFAULT should be "\r\n" 
?>

Also to note that the FROM address must be the same as smtp_user

Chris Muench
  • 17,444
  • 70
  • 209
  • 362
3

You probably ran php on a Linux machine, if this is the case, you'd need to use following line to override CodeIgniter's configuration parameter

'newline' => "\r\n", //must have for office365!

I published an article here:

http://aus800.com.au/sending-out-emails-using-codeigniter-from-office365-account/

Don't Panic
  • 13,965
  • 5
  • 32
  • 51
Jason
  • 31
  • 2
0

I cant exactly point out the error. So i posted 3 Methods. Grab the Idea or which Method is worked out.

Method 01

  1. Login in to the Microsoft Online Services Portal.
  2. Click on Outlook
  3. Click Options (upper right corner)
  4. Click on About
  5. There will be a section titled External SMTP setting that looks like:

Image

The important information is:

  • Server name: pod51010.outlook.com (your’s may be different)
  • Port: 587
  • Encryption method: TLS

then

$config['smtp_host'] = '';//change this
$config['smtp_timeout'] = '5';//fist try with 5 if no response increase to 90 and check

Method 02

$config['protocol'] = 'smtp';
$config['smtp_host'] = 'smtp.office365.com';
$config['smtp_user'] = '****';
$config['smtp_pass'] = '****';
$config['smtp_port'] = '465';//change this
$config['smtp_timeout'] = '60';
$config['smtp_crypto'] = 'tls';

SSL/TLS vs plaintext/STARTTLS port numbers

Method 03

$config['protocol'] = 'smtp';
$config['smtp_host'] = 'tls://smtp.office365.com';//change this
$config['smtp_user'] = '****';
$config['smtp_pass'] = '****';
$config['smtp_port'] = '587';
$config['smtp_timeout'] = '60';
$config['smtp_crypto'] = 'tls';//not sure about this, if not work remove this and try once
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
  • Thank you for your reply. This is all I can find in the Online Service Portal: `POP and IMAP settings: SMTP setting Server name: smtp.office365.com Port: 587 Encryption method: TLS ` I've tried changing the settings (host, port, crypto) and double checked the login credentials, but the problem is still here. No matter what I do, I always get the same error (after the page is loading for a long time): "stream_socket_enable_crypto(): SSL: crypto enabling timeout" Keep in mind, I can easily send out an email using Phpmailer script with the same settings on the same server! – rannt Jun 30 '15 at 07:53
  • you can use gmail instead of outlook – Abdulla Nilam Jun 30 '15 at 07:57
  • Unfortunately I can't, I need to send out emails through our company mail, which is hosted at Microsoft. – rannt Jun 30 '15 at 08:11
  • 1
    That will be my last resort. I don't see the point in using and external library, if the one in Codeogniter is perfectly fine. I know this problem is somehow related to server settings, but I don't know much about servers and I can't figure it out. – rannt Jun 30 '15 at 08:18
0
continue with this tested code

  <?php
     $mail= new phpmailer();  
     $mail->isSMTP();
     $mail->Host = 'smtp.office365.com'; 
     $mail->Port       = 587;
     $mail->SMTPSecure = 'tls';
     $mail->SMTPAuth   = true;
     $mail->Username = 'alertas@xxx.com';
     $mail->Password = 'Password';
     $mail->SetFrom('alertas@xxx.com', 'FromEmail'`enter code here`);
     $mail->addAddress('x@xxx.com', 'ToEmail');
     $mail->IsHTML(true);
$mail->Subject = 'Correo desde PHP';
$mail->Body    = 'Prueba de correo desde php</b>';       

if(!$mail->send()) { 
  echo "Ok"; 
} else { 
   echo "Error";
}
?>
0

For those facing same problem to connect Office365 smtp on 2019 and after: I resolved my problem just using PHPMailer Class. I tested everything here and in another questions and nothing. Uploaded PHPMailer Folder, set up config files and boom. Emails works. Using codeigniter 3.10 and problem seems to remain since this is a old question. In their Email class (codeigniter) have a comment that seems smtp connect is not very good...

/**
* STREAM_CRYPTO_METHOD_TLS_CLIENT is quite the mess ...
*
* - On PHP <5.6 it doesn't even mean TLS, but SSL 2.0, and there's no option to use actual TLS
* - On PHP 5.6.0-5.6.6, >=7.2 it means negotiation with any of TLS 1.0, 1.1, 1.2
* - On PHP 5.6.7-7.1.* it means only TLS 1.0
*
* We want the negotiation, so we'll force it below ...
*/

I don't speak english very well but this seems little confusing.

Ok, so, if you don't want to lose more time, upload PHPMailer Folder you can download at: https://github.com/PHPMailer/PHPMailer

Upload your PHPMailer folder to application/libraries/ and create a file there too:

MY_phpmailer.php

In MY_phpmailer.php file:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_PHPMailer {
        public function My_PHPMailer() {
        require_once('Phpmailer/class.phpmailer.php');
    }
}
?>

PHPMailer send function:

public  function sendmail2($to,$subject,$message,$reply=null,$nameReply=null){

    $this->CI->load->library('MY_phpmailer');

    //$this->load->library('MY_phpmailer'); (If you use this function inside CI, use this instead above) I use CI->load above because my function is in a function_helper, not on controller

    $mail = new PHPMailer();
    $mail->IsSMTP(); //Definimos que usaremos o protocolo SMTP para envio.
    $mail->SMTPDebug = 0;
    $mail->CharSet = 'UTF-8';
    $mail->SMTPAuth = true; //Habilitamos a autenticaçăo do SMTP. (true ou false)
    $mail->SMTPSecure = "tls"; //Estabelecemos qual protocolo de segurança será usado.
    $mail->Host = "smtp.office365.com"; //Podemos usar o servidor do gMail para enviar.
    $mail->Port = 587; //Estabelecemos a porta utilizada pelo servidor do gMail.
    $mail->Username = "your_email@yourdomain.com.br"; //Usuário do gMail
    $mail->Password = "Strong_Password"; //Senha do gMail

    if($reply != null and $nameReply != null){
        //add replyto if you send those values, so you can set other reply address than senders address
        $mail->AddReplyTo($reply, $nameReply);
    }

    $mail->SetFrom('your_email@yourdomain.com.br', 'Senders Name'); //Quem está enviando o e-mail.
    $mail->Subject =  $subject;
    $mail->IsHTML(true); 
    $mail->Body = $message;
    //$mail->AltBody = "Plain text.";
    $mail->AddAddress($to);

    /*If you want to put attachments that comes from a input FILE type name='file'.*/
    if (isset($_FILES['file']) &&
        $_FILES['file']['error'] == UPLOAD_ERR_OK) {
        $mail->AddAttachment($_FILES['file']['tmp_name'],
                             $_FILES['file']['name']);
    }

    if(!$mail->Send()) {
        // error occur - user your show method to show error
        set_msg('msgerro', $mail->ErrorInfo, 'erro');
    } else {
        // success occur - user your show method to show success
        set_msg('msgok', 'E-mail enviado.', 'sucesso');
    }

}

Ok, to finish, on controller that you'd want to use this send function:

$this->load->library("MY_phpmailer");

And in your view, when you want to send e-mails:

$this->system->sendmail2($to, $subject, $message); //$to, $subject and $message are vars you sent from your backend - prefer HTML to $message
Felipe Lima
  • 443
  • 1
  • 10
  • 19