ivantcholakov/codeigniter-phpmailer

一个兼容CodeIgniter 3的电子邮件库,由PHPMailer提供支持。

v1.5.0 2022-08-25 03:11 UTC

This package is auto-updated.

Last update: 2024-09-25 07:54:40 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License

由PHPMailer提供支持的兼容CodeIgniter的电子邮件库

版本:1.5.0
作者:Ivan Tcholakov ivantcholakov@gmail.com,2012-2022.
许可证:MIT许可证 (MIT),https://open-source.org.cn/licenses/MIT

此库兼容CodeIgniter 3.1.x和PHP >= 7.3.0。

在CodeIgniter 3.1.13(2022年3月3日)和PHPMailer版本6.6.4(2022年8月22日)上进行了测试。

链接

包:https://packagist.org.cn/packages/ivantcholakov/codeigniter-phpmailer

PHPMailer:https://github.com/PHPMailer/PHPMailer

安装

启用Composer以供CodeIgniter使用。检查其文档中的此页面: https://www.codeigniter.com/userguide3/general/autoloader.html 。您需要查看或决定您的vendor/目录的位置,并在CodeIgniter的配置文件application/config/config.php中相应地设置配置选项 $config['composer_autoload']。对于典型的位置application/vendor/,配置设置可能如下所示

$config['composer_autoload'] = APPPATH.'vendor/autoload.php';

在application/config/constants.php中添加以下行

// Path to Composer's vendor/ directory, it should end with a trailing slash.
defined('VENDORPATH') OR define('VENDORPATH', rtrim(str_replace('\\', '/', realpath(dirname(APPPATH.'vendor/autoload.php'))), '/').'/');

假设Composer的vendor/目录位于CodeIgniter的应用程序/目录下。否则,请纠正设置,使VENDORPATH指向正确的位置。

如果PHPMailer之前是通过Composer安装的,请暂时卸载它

composer remove PHPMailer/PHPMailer

现在安装此库的包,它将安装正确的PHPMailer版本

composer require ivantcholakov/codeigniter-phpmailer

创建一个名为application/helpers/MY_email_helper.php的文件,内容如下

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

// A place where you can move your custom helper functions,
// that are to be loaded before the functions below.
// If it is needed, create the corresponding file, insert
// your source there and uncomment the following lines.
//if (is_file(dirname(__FILE__).'/MY_email_helper_0.php')) {
//    require_once dirname(__FILE__).'/MY_email_helper_0.php';
//}

// Instead of copying manually or through script in this directory,
// let us just load here the provided by Composer file.
if (is_file(VENDORPATH.'ivantcholakov/codeigniter-phpmailer/helpers/MY_email_helper.php')) {
    require_once VENDORPATH.'ivantcholakov/codeigniter-phpmailer/helpers/MY_email_helper.php';
}

// A place where you can move your custom helper functions,
// that are to be loaded after the functions above.
// If it is needed, create the corresponding file, insert
// your source there and uncomment the following lines.
//if (is_file(dirname(__FILE__).'/MY_email_helper_2.php')) {
//    require_once dirname(__FILE__).'/MY_email_helper_2.php';
//}

创建一个名为application/libraries/MY_Email.php的文件,内容如下

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

// Instead of copying manually or through script in this directory,
// let us just load here the provided by Composer file.
require_once VENDORPATH.'ivantcholakov/codeigniter-phpmailer/libraries/MY_Email.php';

这是一次性安装。更新到下一个版本的此包和PHPMailer将很容易完成

composer update

配置和发送电子邮件(示例)

如果需要,创建或编辑文件application/config/email.php,该文件包含电子邮件引擎的默认设置。对于Gmail账户,设置可能如下所示

<?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']        = 'smtp.gmail.com';
$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']        = 'yourusername@gmail.com';
$config['smtp_pass']        = '';                       // Gmail disabled the so-called "Less Secured Applications", your Google password is not to be used directly, XOAUTH2 authentication will be used.
$config['smtp_port']        = 587;
$config['smtp_timeout']     = 30;                       // (in seconds)
$config['smtp_crypto']      = 'tls';                    // '' or 'tls' or 'ssl'
$config['smtp_debug']       = 0;                        // 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'.

// XOAUTH2 mechanism for authentication.
// See https://github.com/PHPMailer/PHPMailer/wiki/Using-Gmail-with-XOAUTH2
$config['oauth_type']          = 'xoauth2_google';      // XOAUTH2 authentication mechanism:
                                                        // ''                  - disabled;
                                                        // 'xoauth2'           - custom implementation;
                                                        // 'xoauth2_google'    - Google provider;
                                                        // 'xoauth2_yahoo'     - Yahoo provider;
                                                        // 'xoauth2_microsoft' - Microsoft provider.
$config['oauth_instance']      = null;                  // Initialized instance of \PHPMailer\PHPMailer\OAuth (OAuthTokenProvider interface) that contains a custom token provider. Needed for 'xoauth2' custom implementation only. 
$config['oauth_user_email']    = '';                    // If this option is an empty string or null, $config['smtp_user'] will be used.
$config['oauth_client_id']     = '237644427849-g8d0pnkd1jh3idcjdbopvkse2hvj0tdp.apps.googleusercontent.com';
$config['oauth_client_secret'] = 'mklHhrns6eF-qjwuiLpSB4DL';
$config['oauth_refresh_token'] = '1/7Jt8_RHX86Pk09VTfQd4O_ZqKbmuV7HpMNz-rqJ4KdQMEudVrK5jSpoR30zcRFq6';

// DKIM Signing
$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.

注意:将 $config['useragent'] 设置为 'PHPMailer' 以使用PHPMailer引擎。如果需要加密SMTP访问,应启用PHP openssl模块。

在控制器中粘贴以下代码进行测试

$this->load->library('email');

$subject = 'This is a test';
$message = '
    <p>This message has been sent for testing purposes.</p>

    <!-- Attaching an image example - an inline logo. -->
    <p><img src="cid:logo_src" /></p>
';

// Get full html:
$body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=' . strtolower(config_item('charset')) . '" />
    <title>' . html_escape($subject) . '</title>
    <style type="text/css">
        body {
            font-family: Arial, Verdana, Helvetica, sans-serif;
            font-size: 16px;
        }
    </style>
</head>
<body>
' . $message . '
</body>
</html>';
// Also, for getting full html you may use the following internal method:
//$body = $this->email->full_html($subject, $message);

// Attaching the logo first.
$file_logo = FCPATH.'apple-touch-icon-precomposed.png';  // Change the path accordingly.
// The last additional parameter is set to true in order
// the image (logo) to appear inline, within the message text:
$this->email->attach($file_logo, 'inline', null, '', true);
$cid_logo = $this->email->get_attachment_cid($file_logo);
$body = str_replace('cid:logo_src', 'cid:'.$cid_logo, $body);
// End attaching the logo.

$result = $this->email
    ->from('yourusername@gmail.com')
    ->reply_to('yoursecondemail@somedomain.com')    // Optional, an account where a human being reads.
    ->to('therecipient@otherdomain.com')
    ->subject($subject)
    ->message($body)
    ->send();

var_dump($result);
echo '<br />';
echo $this->email->print_debugger();

exit;

加载相应的页面,执行此代码。检查是否已发送电子邮件。如果有的话,读取错误消息并相应地修改您的设置。

请注意,大多数SMTP服务器要求消息的“from”地址与 $config['smtp_user'] 设置中的地址相同。

最后,请删除此测试。

此库的API与原始电子邮件API相同。请参阅CodeIgniter手册中的电子邮件类

为了支持CodeIgniter 2.x和CodeIgniter 3.0.x,需要手动安装此库的较旧版本,请参阅https://github.com/ivantcholakov/codeigniter-phpmailer/tree/1.3-stable