sending email via gmail smtp server with codeignit

2019-07-18 16:05发布

问题:

I have been been trying send email by using gmail smtp server on codeigniter framework.

it working perfect testing on localhost . When I test it on server I got this error

"A PHP Error was encountered

Severity: Warning

Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gmail.com:465 (Connection timed out)

Filename: libraries/Email.php

Line Number: 1689 "

my code is

    $ci = get_instance();
    $ci->load->library('email');
    $config['protocol'] = "smtp";
    $config['smtp_host'] = "ssl://smtp.gmail.com";
    $config['smtp_port'] = "465";
    $config['smtp_user'] = "ticket@gmail.com";
    $config['smtp_pass'] = "test123";
    $config['charset'] = "utf-8";
    $config['mailtype'] = "html";
    $config['newline'] = "\r\n";

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

    $ci->email->from('sender@gmail.com', 'Myanmar Bus Ticket');
    $list = array('receiver@gmail.com');
    $ci->email->to($list);
    $ci->email->reply_to('my-email@gmail.com', 'Explendid Videos');
    $ci->email->subject('This is an email test');
    $ci->email->message('It is working. Great!');

    $ci->email->send();

highly appreciate for all of your help

回答1:

I have found the following:

To use Google SMTP in CodeIgniter you need to make 2 (two) changes into your Gmail account setting: (N.B. Please be aware that it is now easier for an attacker to break into your account -says Google)

  1. Set off 2-step Verification.
  2. Allow less secure apps: ON (or Enable)

Now use 'smtp_host' as ssl://smtp.gmail.com instead of smtp.googlemail.com

Hope this will help upcoming visitor.



回答2:

Create a file in application/config/email.php with the following:

<?php

$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.gmail.com';   //examples: ssl://smtp.googlemail.com, myhost.com
$config['smtp_user'] = 'user@gmail.com';
$config['smtp_pass'] = 'password';
$config['smtp_port'] = '465';
$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"

?>