如何在CodeIgniter中检查收件人电子邮件是否真实?

时间:2016-12-22 03:42:03

标签: php email codeigniter-3

如何在CodeIgniter3中发送邮件时检查收件人电子邮件是否真实?如果它不可用或不是真实的[假]邮件地址,则显示警告框,邮件不可用。

例如:当我们使用虚假邮件地址[不可用或不真实]在gmail中发送邮件时,gmail会回复以下文字。

  

Google试图传递您的邮件,但mta5.am0.example.net的服务器拒绝了收件人域example.com。

编辑1

这是我的电子邮件发送代码。请指导我添加该代码的位置。我按照你的说法添加但是显示

  

未定义的电子邮件变量。

我的电子邮件发送以下代码:

<?php defined('BASEPATH') or exit('No direct script access allowed');
 /**
 * SENDS EMAIL WITH GMAIL
 */
class Emailsend extends CI_Controller
{
  function __construct()
  {
    parent::__construct();
    $this->load->model('emailsend_model');
}

function index()
{
    $mail_setting = $this->emailsend_model->getMailSetting();

    $config = Array(
        'protocol'     => 'smtp',
        //'smtp_host'    => $mail_setting->smtp_server_name,
        'smtp_host'    => 'ssl://smtp.googlemail.com',
        //'smtp_port'    => 465,
        'smtp_port'    => 465,
        //'smtp_user'    => $mail_setting->smtp_user_name,
        'smtp_user'    => 'kzwkyawzinwai@gmail.com',
        //'smtp_pass'    => $mail_setting->smtp_password,
        'smtp_pass'    => 'mypassword',
        'smtp_timeout' => '7',
        'mailtype'     => 'text',
        'validation'   => TRUE,
        'charset'      => 'utf-8',
        'newline'      => "\r\n",
        'wordwrap'     => TRUE,
        'crlf'         => "\r\n",
        'newline'      => "\r\n",
        'dsn'          => TRUE
    );  

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


    date_default_timezone_set("Asia/Tokyo");
    $day = date('Y-m-d');
    //$hour = date('H:i:00');
    //$mail_informs = $this->emailsend_model->getSendMailInfo($day, $hour);
    $mail_informs = $this->emailsend_model->getSendMailInfo($day);
    if(!empty($mail_informs)){

        function calculate_string($mathString) {
            $mathString = trim($mathString);
            $mathString = preg_replace('/[^0-9.\+\-\*\/\(\)]/', '', $mathString);
            $compute = create_function("", "return (". $mathString .");");

            return 0 + $compute();
        }

        foreach($mail_informs as $mail_inform)
        {

            $message = $mail_inform->subject;
            $search_word = array("(氏名)", "(メールアドレス)", "(登録日)");
            $mail_date = str_replace("-", '/', $mail_inform->insert_date);
            $replace_word = array($mail_inform->user_name, $mail_inform->mail_addr, $mail_date);
            $item_informs = $this->emailsend_model->getAllOriginalItemsById($mail_inform->user_plan_detail_id);

            foreach($item_informs as $item_inform){
                $item_name = "(". $item_inform->item_name . ")";

                if($item_inform->data_type==2){
                    $item_value_date = $item_inform->item_value;
                    $item_value = str_replace("-", "/", $item_value_date);
                }
                else if($item_inform->data_type==1){
                    $item_value = $item_inform->item_value;
                    $item_name = str_replace(str_split('()'), '', $item_name);
                }
                else if($item_inform->data_type==0){
                    $item_value = $item_inform->item_value;
                }
                array_push($search_word, $item_name);
                array_push($replace_word, $item_value);
            }


            $result_message = str_replace($search_word, $replace_word, $message);
            preg_match_all("/\(([^)]*)\)/", $result_message, $matches);
            $search_matches = $matches[0];
            $cal_arr = $matches[1];
            $cal_count = count($cal_arr);
            $replace_matches = array();

            for($i=0;$i<$cal_count;$i++)
            {
                $cal_val = calculate_string($cal_arr["$i"]); 
                array_push($replace_matches, $cal_val);
            }

            $final_message = str_replace($search_matches, $replace_matches, $result_message);

            $this->email->set_newline("\r\n");
            $this->email->from( $mail_setting->sender_mail_addr);
            $this->email->to($mail_inform->mail_addr);

          $this->email->subject(mb_convert_encoding($mail_inform->title, "UTF-8"));
            $this->email->message(mb_convert_encoding($final_message, "UTF-8"));

            $path = __DIR__;
            $file = $path . '/../../uploads/'.$mail_inform->tpl_id.'/'.$mail_inform->file_attachment;

            if(!empty($mail_inform->file_attachment)) {
                $this->email->attach($file);
            }

            $r=@$this->email->send();

            if (!$r) {
                ?>
                    <script type="text/javascript">
                        alert("Send Failed");
                    </script>
                <?php
                show_error($this->email->print_debugger());
            }
            else{
                ?>
                    <script type="text/javascript">
                        alert("Send Successfully");
                    </script>
                <?php
                echo $this->email->print_debugger();
                 //show_error($this->email->print_debugger());
            }

            /*if($r) {
                $status = 2; // 送信済み
                $id = $mail_inform->user_plan_detail_id;
                $this->emailsend_model->setStatus($id, $status);
                ?>
                    <script type="text/javascript">
                        alert("Send Successfully");
                    </script>
                <?php

            } 
            else {
                $status = 1; // 送信失敗
                $id = $mail_inform->user_plan_detail_id;
                $this->emailsend_model->setStatus($id, $status);
                ?>
                    <script type="text/javascript">
                        alert("Send Failed");
                    </script>
                <?php
                show_error($this->email->print_debugger());
            }*/
            $this->email->clear(TRUE);
        }
    }

}
}

enter image description here

1 个答案:

答案 0 :(得分:0)

另一种可能的解决方案(在codeigniter之外)使用会返回true或false的公共api,如https://mailjagger.com/api/validate/rajehs@mta5.am0.example.net。只需执行邮件发送部分一旦收到即可。

<强>更新: 在名为Genuinemail.php的库文件夹中创建一个php文件。内容如下

class Genuinemail {
    public function __construct() {
        // Do your stuff with $arr
    }

    /**
     * verify email format, dns and banned emails
     * @param  string $email 
     * @return mixed   bool true if correct / string
     */
    public static function check($email)
    {
        //get the email to check up, clean it
        $email = filter_var($email,FILTER_SANITIZE_STRING);

        // 1 - check valid email format using RFC 822
        if (filter_var($email, FILTER_VALIDATE_EMAIL)===FALSE) 
            return 'No valid email format';

        //get email domain to work in nexts checks
        $email_domain = preg_replace('/^[^@]++@/', '', $email);

        // 2 - check if its from banned domains.
        if (in_array($email_domain,self::get_banned_domains()))
            return 'Banned domain '.$email_domain;

        // 3 - check DNS for MX records
        if ((bool) checkdnsrr($email_domain, 'MX')==FALSE)
            return 'DNS MX not found for domain '.$email_domain;

        // 4 - wow actually a real email! congrats ;)
        return TRUE;
    }

     /**
     * gets the array of not allowed domains for emails, reads from json stores file for 1 week
     * @return array 
     * @see banned domains https://github.com/ivolo/disposable-email-domains/blob/master/index.json
     * @return array
     */
    private static function get_banned_domains()
    {
        //where we store the banned domains
        $file = 'banned_domains.json';

        //if the json file is not in local or the file exists but is older than 1 week, regenerate the json
        if (!file_exists($file) OR (file_exists($file) AND filemtime($file) < strtotime('-1 week')) )
        {
            $banned_domains = file_get_contents("https://rawgit.com/ivolo/disposable-email-domains/master/index.json");
            if ($banned_domains !== FALSE)
                file_put_contents($file,$banned_domains,LOCK_EX);
        }
        else//get the domains from the file
            $banned_domains = file_get_contents($file);

        return json_decode($banned_domains);
    }
}

此库可以像此示例方法一样使用

function checkSpam($email)
    {
        $this->load->library('genuinemail');
        $check = $this->genuinemail->check($email);
        if($check===TRUE) return true;
        return false;

    }