Home > Backend Development > PHP Tutorial > How to read and match email content using PHP

How to read and match email content using PHP

墨辰丷
Release: 2023-03-31 12:00:02
Original
2863 people have browsed it

This article mainly introduces the method of reading and regularly matching email content in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

The example in this article describes how PHP processes postfix email content. The details are as follows:

<?php
//从输入读取到所有的邮件内容
$email = "";
$fd = fopen("php://stdin", "r");
while (!feof($fd)) {
 $email .= fread($fd, 1024);
}
fclose($fd);
//记录所有的内容,测试
file_put_contents("/tmp/mail/".time(), $email);
//处理邮件
$lines = explode("\n", $email);
// empty vars
$from = "";
$date = "";
$subject = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i<count($lines); $i++) {
 if ($splittingheaders) {
  // look out for special headers
  if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
   $subject = $matches[1];
  }
  if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
   if(strpos($lines[$i],"<")){
    //the name exist too in from header
    $data = explode(&#39;<&#39;,$lines[$i]);
    $from = substr(trim($data[1]),0,-1);
   }else{
    //only the mail
    $from = $matches[1];
   }
  }
  if (preg_match("/^Date: (.*)/", $lines[$i], $matches)) {
   $date = $matches[1];
  }
 } else {
  // not a header, but message
  $message .= $lines[$i]."\n";
 }
 if (trim($lines[$i])=="") {
  // empty line, header section has ended
  $splittingheaders = false;
 }
}
$when = date("Y-m-d G:i:s");
$data = explode(&#39;@&#39;,$from);
$username = $data[0];
//记录到数据库
$sql = "insert into mails ( `username`, `from`, `subject`, `date`, `message`) values ( &#39;$username&#39;, &#39;$from&#39;, &#39;$subject&#39;, &#39;$when&#39;, &#39;$message&#39;)";
//测试
file_put_contents("/tmp/mail2.log", $sql);
?>
Copy after login

Summary: The above is the entire content of this article, I hope it can be helpful to everyone’s learning help.

Related recommendations:

Basic knowledge of Socket in PHP

##php implementation Function of sending and receiving text messages

php reversible encryption method and principle

##

The above is the detailed content of How to read and match email content using PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template