Hướng dẫn php imap gmail example - ví dụ về gmail php imap

set_time_limit(4000); 

// Connect to gmail
$imapPath = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '';
$password = 'your_gmail_password';

// try to connect 
$inbox = imap_open($imapPath,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

   /* ALL - return all messages matching the rest of the criteria
    ANSWERED - match messages with the \\ANSWERED flag set
    BCC "string" - match messages with "string" in the Bcc: field
    BEFORE "date" - match messages with Date: before "date"
    BODY "string" - match messages with "string" in the body of the message
    CC "string" - match messages with "string" in the Cc: field
    DELETED - match deleted messages
    FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set
    FROM "string" - match messages with "string" in the From: field
    KEYWORD "string" - match messages with "string" as a keyword
    NEW - match new messages
    OLD - match old messages
    ON "date" - match messages with Date: matching "date"
    RECENT - match messages with the \\RECENT flag set
    SEEN - match messages that have been read (the \\SEEN flag is set)
    SINCE "date" - match messages with Date: after "date"
    SUBJECT "string" - match messages with "string" in the Subject:
    TEXT "string" - match messages with text "string"
    TO "string" - match messages with "string" in the To:
    UNANSWERED - match messages that have not been answered
    UNDELETED - match messages that are not deleted
    UNFLAGGED - match messages that are not flagged
    UNKEYWORD "string" - match messages that do not have the keyword "string"
    UNSEEN - match messages which have not been read yet*/

// search and get unseen emails, function will return email ids
$emails = imap_search($inbox,'UNSEEN');

$output = '';

foreach($emails as $mail) {

    $headerInfo = imap_headerinfo($inbox,$mail);

    $output .= $headerInfo->subject.'
'; $output .= $headerInfo->toaddress.'
'; $output .= $headerInfo->date.'
'; $output .= $headerInfo->fromaddress.'
'; $output .= $headerInfo->reply_toaddress.'
'; $emailStructure = imap_fetchstructure($inbox,$mail); if(!isset($emailStructure->parts)) { $output .= imap_body($inbox, $mail, FT_PEEK); } else { // } echo $output; $output = ''; } // colse the connection imap_expunge($inbox); imap_close($inbox);

For using this you need to install and enable

apt-get install php5-imap
1

You can install the PHP5 IMAP module with this command :

apt-get install php5-imap

However it’s not enabled by default so enable it with:

php5enmod imap

To see the changes ,restart Apache

service apache2 restart

For Windows with Xampp7 and above,

Go to php.ini, Remove the semicolon,php.ini, Remove the semicolon,

;extension=imap

Trong trường hợp chúng ta cần sử dụng chức năng về email thông qua các Email Provider (Gmail, Yandex, Yahoo, AOL, ...) , thì  PHP IMAP là một giải pháp tốt nhất  nó một extension của PHP để lấy mail từ hệ thống. Trong bài viết này mình sẽ sử dụng thư viện php-imap/php-imap

Cài đặt

  1. Nếu chưa cài đặt thư viện php-imap thì bạn có thể cài đặt bằng câu lệnh sau (dấu * là phiên bản php muốn cài đặt) :
sudo apt-get install php*-imap php*-mbstring php*-mcrypt && sudo apache2ctl graceful

Để chắc chắn thì bạn có thể sử dụng phpinfo() để kiểm tra xem thư viện đã được kích hoạt chưa

  1. Cài đặt php-imap/php-imap package từ github :
composer require php-imap/php-imap

Tính năng hỗ trợ

  • Kết nối với hộp thư bằng POP3 / IMAP / NNTP, sử dụng phần mở rộng PHP IMAP
  • Nhận email có tệp đính kèm và hình ảnh nội tuyến
  • Nhận email được lọc hoặc sắp xếp theo tiêu chí tùy chỉnh
  • Đánh dấu email là đã thấy / chưa nhìn thấy
  • Xóa email
  • Quản lý các thư mục hộp thưuản lý các thư mục hộp thư

Bắt đầu

  1.  Tạo migrations để lưu email được đọc,m ở đây mình tạo 1 bảng có tên 'mails' gồm các trường như sau:
    increments('id');
                $table->bigInteger("mid"); // mail ID
                $table->string('messageId')->unique(); // message id
    			$table->integer('user_server'); // id of curent server
                $table->string('references'); // message id
                $table->string('in_reply_to'); // message id
                $table->dateTime("date");
                $table->string("subject")->nullable();
                $table->string("fromName")->nullable();
                $table->string("fromAddress")->nullable();
                $table->string("to")->nullable();
                $table->string("cc")->nullable();
                $table->string("reply")->nullable();
                $table->text("plain")->nullable();
                $table->text("html")->nullable();
                $table->string('folder')->nullable();
                $table->integer('mess_references')->default(0);
    
    			$table->timestamps();
    		});
    	}
    
    
    	/**
    	 * Reverse the migrations.
    	 *
    	 * @return void
    	 */
    	public function down()
    	{
    		Schema::drop('mails');
    	}
    
    }
    ​

    increments('id');
                $table->bigInteger("mid"); // mail ID
                $table->string('messageId')->unique(); // message id
    			$table->integer('user_server'); // id of curent server
                $table->string('references'); // message id
                $table->string('in_reply_to'); // message id
                $table->dateTime("date");
                $table->string("subject")->nullable();
                $table->string("fromName")->nullable();
                $table->string("fromAddress")->nullable();
                $table->string("to")->nullable();
                $table->string("cc")->nullable();
                $table->string("reply")->nullable();
                $table->text("plain")->nullable();
                $table->text("html")->nullable();
                $table->string('folder')->nullable();
                $table->integer('mess_references')->default(0);
    
    			$table->timestamps();
    		});
    	}
    
    
    	/**
    	 * Reverse the migrations.
    	 *
    	 * @return void
    	 */
    	public function down()
    	{
    		Schema::drop('mails');
    	}
    
    }
    ​
  2. Tạo bảng 'mail_attachments' để lưu các tệp tin từ các mail được đọc
    increments('id');
    			$table->integer("mail_id")->unsigned();
                $table->string("aid")->unique();
                $table->string("name")->nullable();
                $table->string("path")->nullable();
    
    			$table->timestamps();
    		});
    	}
    
    
    	/**
    	 * Reverse the migrations.
    	 *
    	 * @return void
    	 */
    	public function down()
    	{
    		Schema::drop('mail_attachments');
    	}
    
    }
    ​

    increments('id');
    			$table->integer("mail_id")->unsigned();
                $table->string("aid")->unique();
                $table->string("name")->nullable();
                $table->string("path")->nullable();
    
    			$table->timestamps();
    		});
    	}
    
    
    	/**
    	 * Reverse the migrations.
    	 *
    	 * @return void
    	 */
    	public function down()
    	{
    		Schema::drop('mail_attachments');
    	}
    
    }
    ​
  3. Tạo command 'mails:GetMail' để kết nối với server mail , đọc mail và lưu vào cơ sở dữ liệu
    searchMailBox('ALL');
            // }
            if(!$mailIds) {
                $this->info("No mail!");
            } else {
                $list_message = $mailbox->getMailsInfo($mailIds);
                $check_references = Mail::where('user_server', 1)->pluck('messageId', 'id')->toArray();
                foreach ($list_message as  $value) {
                    if(Mail::where("messageId", $value->message_id)->count() == 0) {
                        $getMail = $mailbox->getMail($value->uid);
    
                        $ccs = [];
                        foreach($getMail->cc as $ccMail => $ccName) {
                            $ccs[] = $ccName."(".$ccMail.")";
                        }
                        $replys = [];
                        foreach($getMail->replyTo as $replyMail => $replyName) {
                            $replys[] = $replyName."(".$replyMail.")";
                        }
                        $mess_references = 0;
                        $current_references = explode(' ', $value->references??'');
                        if(count($current_references) > 0 && count($check_references) > 0) {
                            foreach ($check_references as $key => $ref) {
                                if($current_references[0] == $ref) {
                                    $mess_references = $key;
                                }
                            }
                        }
                        $mail = new Mail;
                        $mail->mid = $getMail->id;
                        $mail->messageId = $value->message_id;
                        $mail->user_server = 1;
                        $mail->references = $value->references ?? '';
                        $mail->in_reply_to = $value->in_reply_to ?? '';
                        $mail->date = date('Y-m-d H:i:s', strtotime($value->date));
                        $mail->subject = $getMail->subject ?? '';
                        $mail->fromName = $getMail->fromName ?? '';
                        $mail->fromAddress = $getMail->fromAddress ?? '';
                        $mail->to = $value->to ?? '';
                        $mail->cc = implode(",", $ccs);
                        $mail->reply = implode(",", $replys);
                        $mail->plain = $getMail->textPlain ?? '';
                        $mail->html = json_encode($getMail->textHtml ?? '');
                        $mail->folder = 'inbox';
                        $mail->mess_references = $mess_references ?? 0;
                        $mail->save();
    
                        $check_references[$mail->id] = $value->message_id;
    
                        foreach($getMail->getAttachments() as $getAttachment) {
                            $attachment = new MailAttachment();
                            $attachment->aid = $getAttachment->id;
                            $attachment->name = $getAttachment->name;
                            $attachment->path = $getAttachment->filePath;
                            $attachment->mail_id = $mail->id;
                            $attachment->save();
                        }
    
                        $this->info("New Mail:".$mail->subject);
                    }
                }
            }
            \Log::info('End get inbox');
    
        }
    }
    ​

    searchMailBox('ALL');
            // }
            if(!$mailIds) {
                $this->info("No mail!");
            } else {
                $list_message = $mailbox->getMailsInfo($mailIds);
                $check_references = Mail::where('user_server', 1)->pluck('messageId', 'id')->toArray();
                foreach ($list_message as  $value) {
                    if(Mail::where("messageId", $value->message_id)->count() == 0) {
                        $getMail = $mailbox->getMail($value->uid);
    
                        $ccs = [];
                        foreach($getMail->cc as $ccMail => $ccName) {
                            $ccs[] = $ccName."(".$ccMail.")";
                        }
                        $replys = [];
                        foreach($getMail->replyTo as $replyMail => $replyName) {
                            $replys[] = $replyName."(".$replyMail.")";
                        }
                        $mess_references = 0;
                        $current_references = explode(' ', $value->references??'');
                        if(count($current_references) > 0 && count($check_references) > 0) {
                            foreach ($check_references as $key => $ref) {
                                if($current_references[0] == $ref) {
                                    $mess_references = $key;
                                }
                            }
                        }
                        $mail = new Mail;
                        $mail->mid = $getMail->id;
                        $mail->messageId = $value->message_id;
                        $mail->user_server = 1;
                        $mail->references = $value->references ?? '';
                        $mail->in_reply_to = $value->in_reply_to ?? '';
                        $mail->date = date('Y-m-d H:i:s', strtotime($value->date));
                        $mail->subject = $getMail->subject ?? '';
                        $mail->fromName = $getMail->fromName ?? '';
                        $mail->fromAddress = $getMail->fromAddress ?? '';
                        $mail->to = $value->to ?? '';
                        $mail->cc = implode(",", $ccs);
                        $mail->reply = implode(",", $replys);
                        $mail->plain = $getMail->textPlain ?? '';
                        $mail->html = json_encode($getMail->textHtml ?? '');
                        $mail->folder = 'inbox';
                        $mail->mess_references = $mess_references ?? 0;
                        $mail->save();
    
                        $check_references[$mail->id] = $value->message_id;
    
                        foreach($getMail->getAttachments() as $getAttachment) {
                            $attachment = new MailAttachment();
                            $attachment->aid = $getAttachment->id;
                            $attachment->name = $getAttachment->name;
                            $attachment->path = $getAttachment->filePath;
                            $attachment->mail_id = $mail->id;
                            $attachment->save();
                        }
    
                        $this->info("New Mail:".$mail->subject);
                    }
                }
            }
            \Log::info('End get inbox');
    
        }
    }
    ​
  4. Kết quả
    apt-get install php5-imap
    
    0
    apt-get install php5-imap
    
    0

kết luận

Như vậy với những thao tác đơn giản mình có thể hoàn toàn đọc mail và lưu mail về cơ sở dữ liệu để dễ dàng sử dụng

Nguồn  thư viện: https://github.com/barbushin/php-imap