使用 CodeIgniter 通过 Gmail 发送电子邮件时遇到问题?

发布于 2024-11-30 03:45:31 字数 1468 浏览 0 评论 0原文

我正在尝试通过我的 Gmail 帐户在 codeigniter 中发送电子邮件。我当前的代码如下所示:

$config = Array(
     'protocol' => 'smtp',
     'smtp_host' => 'ssl://smtp.googlemail.com',
     'smtp_port' => 465,
     'smtp_user' => '[email protected]',
     'smtp_pass' => 'my_gmail_password',
     'mailtype'  => 'html',
     'charset'   => 'iso-8859-1'
);

$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('[email protected]', 'Me');
$this->email->to("[email protected]");
$this->email->subject('A test email from CodeIgniter using Gmail');
$this->email->message("A test email from CodeIgniter using Gmail");

$this->email->send();

但是,这给了我以下错误:

Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Connection timed out)
Filename: libraries/Email.php

Message: fwrite(): supplied argument is not a valid stream resource

Message: fgets(): supplied argument is not a valid stream resource

任何解决此问题的帮助将不胜感激!谢谢!

注意:我可以向您保证我的 Gmail 电子邮件和密码正确

I'm trying to send an email in codeigniter via my Gmail account. My current code looks like this:

$config = Array(
     'protocol' => 'smtp',
     'smtp_host' => 'ssl://smtp.googlemail.com',
     'smtp_port' => 465,
     'smtp_user' => '[email protected]',
     'smtp_pass' => 'my_gmail_password',
     'mailtype'  => 'html',
     'charset'   => 'iso-8859-1'
);

$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('[email protected]', 'Me');
$this->email->to("[email protected]");
$this->email->subject('A test email from CodeIgniter using Gmail');
$this->email->message("A test email from CodeIgniter using Gmail");

$this->email->send();

However, this gives me the following errors:

Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Connection timed out)
Filename: libraries/Email.php

Message: fwrite(): supplied argument is not a valid stream resource

Message: fgets(): supplied argument is not a valid stream resource

Any help to resolve this issue would be much appreciated! Thanks!

Note: I can assure you that my Gmail email & password are correct

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千仐 2024-12-07 03:45:31

该错误意味着您无法连接您输入的 SMTP 地址。

您应该使用:smtp.gmail.com

检查以下链接以供参考:
http://mail.google.com/support/bin/answer.py ?answer=13287

The error means you cannot connect the the SMTP address you've entered.

you should use: smtp.gmail.com

Check following link for reference:
http://mail.google.com/support/bin/answer.py?answer=13287

决绝 2024-12-07 03:45:31

您可以下载“Shawn McCool”使用“Swift-Mailer”编写的漂亮的小火花包。
查看他的网站以获取安装说明

这是我使用 DRY 方法发送电子邮件的配置(需要 PHP 5.3.0!)。

配置
|--mailer[dot]php

$config['swift_email_server'] = 'ssl://smtp.googlemail.com';
$config['swift_email_port'] = 465;
$config['swift_email_username'] = '######';
$config['swift_email_password'] = '######';


|--MY_Email

    class MY_Email extends CI_Email {


    public function __construct(){
        parent::__construct();

    }
    /**
     * =========================================================================
     * Parse's html email templates - initalised via swift-mailer
     * 
     * @param mixed $data
     * @param string $template
     * @return html
     * 
     * ========================================================================= 
     */
    public function send_mail($data, $template){

        //Anonymous functions are available since PHP 5.3.0
        $callback = function ($matches) use ($data){
            return ( isset($data[$matches[1]]) ) 
               ? $data[$matches[1]] 
               : $matches[0];
        };

        //Finds any matches in brackets [] and replaces them with data passed via callback
        return preg_replace_callback(
                '/\[(.*?)\]/', 
                $callback, 
                read_file(EMAIL_TEMPLATES . $template));

    }


}

Email templates location defined in index.php
define('EMAIL_TEMPLATES', 'emailtemplates');

控制器
|--MY_Controller

    class MY_Controller extends MX_Controller{

        protected $user;

        protected $swiftMailer = NULL;


        public function __construct(){

            parent::__construct();


            $this->user =   ($this->session->userdata('uid'))
                        ?    Member::find($this->session->userdata('uid')) : array();

            $this->setup_profile();


           $this->form_validation->set_error_delimiters('<p class="form-error">', '</p>');


        }

        public function setup_profile(){
            $sections = array(
            'config'  => FALSE,
            'http_headers' => FALSE,
            'queries'  =>  FALSE,
            'memory_usage'  =>  FALSE
            );

            $this->output->set_profiler_sections($sections);

            if(ENVIRONMENT === 'development'){
                $this->output->enable_profiler(TRUE);
            }
        }

    protected function prep_email($data, $template){


            $message = 
            Swift_Message::newInstance('Type your heading here...')
              ->setFrom($data['email_address'])
              ->setTo(array($this->config->item('primary_email'), $data['email_address']))
              ->setBody( $this->email->send_mail($data, $template))
              ->setContentType('text/html');

            return ( $this->swiftMailer->send($message) );


     }


}

模块
|--services // 简单测试模块

public functionarrange() {
$配置=数组(
array('field'=>'service', 'label'=>'Service', 'rules'=>'trim|required|max_lenght[128]'),
array('field'=>'num', 'label'=>'会话数', 'rules'=>'trim|required|numeric'),
array('field'=>'request_date', 'label'=>'Request_date', 'rules'=>'trim|required'),
array('field'=>'注释', 'label'=>'注释', 'rules'=>'trim|max_lenght[500]')
);

    $this->form_validation->CI =& $this; 
    $this->form_validation->set_rules($config); 

    if($this->form_validation->run($this)){

        $service = Service::find($this->input->post('service'));

        if((int)$this->input->post('num') > 1){
            $potential = ( $this->input->post('num') * $service->price );
        }else{
            $potential =    $this->input->post('num');
        }

        $insert = array(
            'service_id'    =>  $this->input->post('service'),
            'num'   =>  $this->input->post('num'),
            'request_date'  =>  $this->input->post('request_date'),
            'note'  =>  serialize( $this->input->post('note') ),
            'potential_income'  =>  $potential,
            'member_id' =>  $this->user->id,
            'status'    =>  'pending'
        );

        $emaildata = array(
            'service'   =>  $service->slug,
            'num'   =>  $insert['num'],
            'request_date'  =>  $insert['request_date'],
            'note'  =>  $insert['note'],
            'potential_income'  =>  $potential,
            'email_address' =>  $this->user->email_address,
            'status'    =>  'pending',
            'fullname'  =>  $this->user->firstname . ' ' . $this->user->surname,
            'message_sent'  =>  date('M d h:iA'),
          'site_link'  =>  ''
        );

        if(Meeting::create($insert)){

            if(parent::prep_email($emaildata, 'request_meeting[dot]html')){
                $this->session->set_flashdata('success' ,'Request has been sent! You will recieve an email shortly from Paul');
                //redirect('/');
            }else{
                $this->session->set_flashdata('error', 'Email service seems to be down at the moment');
                //redirect('/');
            }

        }else{
            $this->session->set_flashdata('error', 'Unable to request meeting at this time');
            //redirect('/');
        }


    }else{
        $this->meetings_form();
    }

希望这有帮助!

You could download a nice little sparks package by "Shawn McCool" that utilizes "Swift-Mailer".
Check out his site for install instructions

Here is my configuration for sending out email's using a DRY approach(PHP 5.3.0 required!).

Config
|--mailer[dot]php

$config['swift_email_server'] = 'ssl://smtp.googlemail.com';
$config['swift_email_port'] = 465;
$config['swift_email_username'] = '######';
$config['swift_email_password'] = '######';

Libarary
|--MY_Email

    class MY_Email extends CI_Email {


    public function __construct(){
        parent::__construct();

    }
    /**
     * =========================================================================
     * Parse's html email templates - initalised via swift-mailer
     * 
     * @param mixed $data
     * @param string $template
     * @return html
     * 
     * ========================================================================= 
     */
    public function send_mail($data, $template){

        //Anonymous functions are available since PHP 5.3.0
        $callback = function ($matches) use ($data){
            return ( isset($data[$matches[1]]) ) 
               ? $data[$matches[1]] 
               : $matches[0];
        };

        //Finds any matches in brackets [] and replaces them with data passed via callback
        return preg_replace_callback(
                '/\[(.*?)\]/', 
                $callback, 
                read_file(EMAIL_TEMPLATES . $template));

    }


}

Email templates location defined in index.php
define('EMAIL_TEMPLATES', 'emailtemplates');

Controller
|--MY_Controller

    class MY_Controller extends MX_Controller{

        protected $user;

        protected $swiftMailer = NULL;


        public function __construct(){

            parent::__construct();


            $this->user =   ($this->session->userdata('uid'))
                        ?    Member::find($this->session->userdata('uid')) : array();

            $this->setup_profile();


           $this->form_validation->set_error_delimiters('<p class="form-error">', '</p>');


        }

        public function setup_profile(){
            $sections = array(
            'config'  => FALSE,
            'http_headers' => FALSE,
            'queries'  =>  FALSE,
            'memory_usage'  =>  FALSE
            );

            $this->output->set_profiler_sections($sections);

            if(ENVIRONMENT === 'development'){
                $this->output->enable_profiler(TRUE);
            }
        }

    protected function prep_email($data, $template){


            $message = 
            Swift_Message::newInstance('Type your heading here...')
              ->setFrom($data['email_address'])
              ->setTo(array($this->config->item('primary_email'), $data['email_address']))
              ->setBody( $this->email->send_mail($data, $template))
              ->setContentType('text/html');

            return ( $this->swiftMailer->send($message) );


     }


}

Module
|--services // simple test module

public function arrange() {
$config = array(
array('field'=>'service', 'label'=>'Service', 'rules'=>'trim|required|max_lenght[128]'),
array('field'=>'num', 'label'=>'Numer of Sessions', 'rules'=>'trim|required|numeric'),
array('field'=>'request_date', 'label'=>'Request_date', 'rules'=>'trim|required'),
array('field'=>'note', 'label'=>'Note', 'rules'=>'trim|max_lenght[500]')
);

    $this->form_validation->CI =& $this; 
    $this->form_validation->set_rules($config); 

    if($this->form_validation->run($this)){

        $service = Service::find($this->input->post('service'));

        if((int)$this->input->post('num') > 1){
            $potential = ( $this->input->post('num') * $service->price );
        }else{
            $potential =    $this->input->post('num');
        }

        $insert = array(
            'service_id'    =>  $this->input->post('service'),
            'num'   =>  $this->input->post('num'),
            'request_date'  =>  $this->input->post('request_date'),
            'note'  =>  serialize( $this->input->post('note') ),
            'potential_income'  =>  $potential,
            'member_id' =>  $this->user->id,
            'status'    =>  'pending'
        );

        $emaildata = array(
            'service'   =>  $service->slug,
            'num'   =>  $insert['num'],
            'request_date'  =>  $insert['request_date'],
            'note'  =>  $insert['note'],
            'potential_income'  =>  $potential,
            'email_address' =>  $this->user->email_address,
            'status'    =>  'pending',
            'fullname'  =>  $this->user->firstname . ' ' . $this->user->surname,
            'message_sent'  =>  date('M d h:iA'),
          'site_link'  =>  ''
        );

        if(Meeting::create($insert)){

            if(parent::prep_email($emaildata, 'request_meeting[dot]html')){
                $this->session->set_flashdata('success' ,'Request has been sent! You will recieve an email shortly from Paul');
                //redirect('/');
            }else{
                $this->session->set_flashdata('error', 'Email service seems to be down at the moment');
                //redirect('/');
            }

        }else{
            $this->session->set_flashdata('error', 'Unable to request meeting at this time');
            //redirect('/');
        }


    }else{
        $this->meetings_form();
    }

Hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文