ThinkPHP邮件发送函数

1.在模块的配置文件config中加入下里面代码

//邮件配置
'THINK_EMAIL' => array(
'SMTP_HOST'   => 'smtp.aaa.com', //SMTP服务器
'SMTP_PORT'   => '465', //SMTP服务器端口
'SMTP_USER'   => '[email protected]', //SMTP服务器用户名
'SMTP_PASS'   => 'password', //SMTP服务器密码
'FROM_EMAIL'  => '[email protected]', //发件人EMAIL
'FROM_NAME'   => 'ThinkPHP', //发件人名称
'REPLY_EMAIL' => '', //回复EMAIL(留空则为发件人EMAIL)
'REPLY_NAME'  => '', //回复名称(留空则为发件人名称)
),

2.在Common目录下创建function.php文件,加入下面代码

 /**
 * 系统邮件发送函数
 * @param string $to    接收邮件者邮箱
 * @param string $name  接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body    邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 */
function think_send_mail($to, $name, $subject = '', $body = '', $attachment = null)
{
    $config = C('THINK_EMAIL');
    vendor('PHPMailer.class#phpmailer'); //从PHPMailer目录导class.phpmailer.php类文件
    $mail          = new \PHPMailer(); //PHPMailer对象
    $mail->CharSet = 'UTF-8'; //设定邮件编码,默认ISO-8859-1,如果发中文此项必须设置,否则乱码
    $mail->IsSMTP(); // 设定使用SMTP服务
    $mail->SMTPDebug = 0; // 关闭SMTP调试功能
    // 1 = errors and messages
    // 2 = messages only
    $mail->SMTPAuth   = true; // 启用 SMTP 验证功能
    $mail->SMTPSecure = 'ssl'; // 使用安全协议
    $mail->Host       = $config['SMTP_HOST']; // SMTP 服务器
    $mail->Port       = $config['SMTP_PORT']; // SMTP服务器的端口号
    $mail->Username   = $config['SMTP_USER']; // SMTP服务器用户名
    $mail->Password   = $config['SMTP_PASS']; // SMTP服务器密码
    $mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
    $replyEmail = $config['REPLY_EMAIL'] ? $config['REPLY_EMAIL'] : $config['FROM_EMAIL'];
    $replyName  = $config['REPLY_NAME'] ? $config['REPLY_NAME'] : $config['FROM_NAME'];
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($to, $name);
    if (is_array($attachment)) {
        // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
  }

3.修改php.int文件

extension=php_openssl.dll
allow_url_fopen = On

重启apache

4.在控制器中使用函数

public function sendmail()
{
    $kk = think_send_mail('[email protected]','序列', $subject = '数据', $body = '1111111');
    var_dump($kk);exit;
}

5.下载扩展PHPMailer解压到ThinkPHP\Library\Vendor
http://www.thinkphp.cn/code/download/id/989.html


可能会出现Fatal error : Class 'SMTP' not found 的错误

/**
 * Get an instance to use for SMTP operations.
 * Override this function to load your own SMTP implementation
 * @return SMTP
 */
public function getSMTPInstance()
{
    require 'PHPMailerAutoload.php'; //引入文件就好
    if (!is_object($this->smtp)) {
        $this->smtp = new SMTP;
    }
    return $this->smtp;
}

你可能感兴趣的:(ThinkPHP邮件发送函数)