发送电子邮件功能


Send Email Function

我有一个用户控制器,用于我的Codeigniter应用程序的前端,用于处理注册、登录、忘记密码、查看(配置文件)页面,我正在努力决定功能发送电子邮件功能的最佳位置。如果某个东西最适合库函数,或者应该放在其他地方。

我问这个问题是因为我真的在努力关注OOP内部的Single Responsibility PrinciplePolymorphism

有人能给我一些最好的建议和/或建议吗?

codeigniter在system/helper/email_helper中有一个本地助手,它提供了一个名为send_email()的函数,该函数使用php-mail()函数。虽然这是非常基本的,但它会让你知道如何设置。

我建议创建一个帮助程序来覆盖本机。即在application/helpers中创建一个MY_email_helper.php,并在其中定义自己的send_email()函数

/**
 * Send an email
 *
 * @access  public
 * @return  bool
 */
if ( ! function_exists('send_email'))
{
    function send_email($recipient, $subject, $message, $from_email = NULL, $from_name = NULL, $method = NULL)
    {
        // Obtain a reference to the ci super object
        $CI =& get_instance();
        switch(strtolower($method))
        {
            /*
             * SES Free Tier allows 2000 emails per day (Up to 10,000 per day)
             * see: http://aws.amazon.com/ses/pricing/
             */
            case 'ses':
                $CI->load->library('aws_lib');
                $sender = $from_email ? ($from_name ? $from_name.' <'.$from_email.'>' : $from_email) : NULL;
                $CI->aws_lib->send_email($recipient, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $sender);
            break;
            /*
             * Mandrill Free Tier allows 12,000 per month
             * see: http://mandrill.com/pricing/
             */
            case 'mandrill':
                // todo...
            break;
            default:
                $CI->load->library('email');
                $CI->email->from($from_email, $from_name);
                $CI->email->to($recipient);
                $CI->email->subject('=?UTF-8?B?'.base64_encode($subject).'?=');
                $CI->email->message($message);
                $CI->email->send();
                log_message('debug', $CI->email->print_debugger());
        }
    }
}

这意味着,如果您已经在使用send_mail()函数,只需加载MY_email_helper,一切都会正常工作。

您可以在application/helpers中自己的助手(称为"general_helper.php")中编写发送电子邮件的通用代码。

然后在config/autoload.php中添加"general_helper"。因此,这个助手文件将在所有地方都可用。帮助程序可能有类,也可能没有类。因此,如果您没有在helper中使用类,您可以直接将sendmail函数调用为

sendmail($to,$from,$sub,$msg,$headers);