网站监控邮件发送方法

网站监控、功能脚本执行结果邮件:

/**
 * 邮件发送方法
 * @param string $title 邮件主题
 * @param string $content 邮件内容
 */
function send_email($title, $content) {
    //如下以get请求发送邮件,链接中不能有&符号,以斜杠替换
    $content = str_replace("&", "/", $content);
    //获取是哪里调用的本方法,可以获取文件、行数、函数名称、参数等信息
    $backtrace = debug_backtrace();
    $send_time = '发送时间: ' . date("Y-m-d H:i:s",time()) . "
"
; $send_ip = '发送服务器: ' . gethostbyname(gethostname()) . "
"
; $content = $send_time . $send_ip . '邮件内容: ' . "
"
. $content; //邮件发送接口,出于安全考虑,邮件接收者最好写死,通过传参不同控制邮件接受者 $sendurl = 'http://api.baidu.com/send_email.php?type=1&title=' . $title . '&content=' . $content; $result = file_get_contents($sendurl); if ('ok' != $result) { //写入php错误记录日志 error_log('PHP Warning: 邮件发送失败 in ' . $backtrace[0]['file'] . ' on line ' . $backtrace[0]['line'] , 0); //自定义记录邮件内容 $message = 'PHP Warning: 邮件发送失败 in ' . $backtrace[0]['file'] . ' on line ' . $backtrace[0]['line'] . "
"
. $content . "\n"; $message = str_replace("
"
, "\n\t", $message); error_log($message, 3, "error.log"); return true; } } send_email('test', 'test');

邮件发送接口可以用 PHPMailer 写,若邮件发送成功,返回 ‘ok’!

还要注意邮件内容大小,发送邮件时对邮件内容字符数有限制

/**
 * 邮件发送方法
 * @param str $title 邮件主题
 * @param str $content 邮件内容
 * @param str $email 单独发送email
 * @param int $type 测试发送设为 1
 */
function sendEmail($title, $content, $email=null, $type=null) {
    $url = 'http://api.baidu.com/send_email.php';
    $post_data = array();
    //要注意  php.ini  中对post请求传值大小的限制
    $content = substr($content, 0, 1024*1000);
    $content = str_replace("&", "/", $content);
    $content = date("Y-m-d H:i:s",time()) . "
"
. $content; !empty($type) ? $post_data['type'] = $type : false; !empty($email) ? $post_data['email'] = $email : false; $post_data['title'] = $title; $post_data['content'] = $content; $result = curlPost($url, $post_data); if('ok' != $result['data']) { $message = date("Y-m-d H:i:s",time()) . __FILE__ . ' 邮件发送失败!!!'; $content = str_replace("
"
, "\n", $content); $message_err = $message . "\n" . $content; error_log($message_err,3,"error.log"); $post_data['title'] = '邮件发送失败通知'; $message .= !empty($result['error']) ? '失败原因 : ' . $result['error'] : ''; $post_data['content'] = $message; curlPost($url, $post_data); } } /** * 发送post请求 * @param str $url * @param array $post_data * @return multitype:mixed string */ function curlPost($url, $post_data) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); $data = curl_exec($curl); $code = curl_getinfo($curl,CURLINFO_HTTP_CODE); $error = curl_error($curl); curl_close($curl); $result = array( 'data' => $data, 'code' => $code, 'error' => $error, ); return $result; }

你可能感兴趣的:(PHP,设计)