6

電子メールをプログラムにパイプし、いくつかのコードを実行しています。

**

「From:」と「Subject:」を取得する方法は知っていますが、メールの本文だけを取得するにはどうすればよいですか?

**

#!/usr/bin/php -q
<?

$fd = fopen("php://stdin", "r");
while (!feof($fd)) {
  $email .= fread($fd, 1024);
}
fclose($fd);

$lines = explode("\n", $email);

for ($i=0; $i < count($lines); $i++) 
{


    // look out for special headers
    if (preg_match("/Subject:/", $lines[$i], $matches)) 
        {

    list($One,$Subject) = explode("Subject:", $lines[$i]);    
    list($Subject,$Gone) = explode("<", $Subject);  


        }

など... メールの本文の内容を取得するにはどうすればよいですか?

4

1 に答える 1

5

基本的に、ヘッダーがどこで終了するか、それがマルチパートかどうかを知りたいので、電子メールの適切な部分を取得できます。

ここにいくつかの情報があります:

PHPで生のメールを解析する

これは、最初の二重改行が電子メールの本文の始まりであることを示しています。

このページでは、他のアイデアが得られるかもしれません (以下のスクリプトを参照してください)。

http://thedrupalblog.com/configuring-server-parse-email-php-script

#!/usr/bin/php
<?php

// fetch data from stdin
$data = file_get_contents("php://stdin");

// extract the body
// NOTE: a properly formatted email's first empty line defines the separation between the headers and the message body
list($data, $body) = explode("\n\n", $data, 2);

// explode on new line
$data = explode("\n", $data);

// define a variable map of known headers
$patterns = array(
  'Return-Path',
  'X-Original-To',
  'Delivered-To',
  'Received',
  'To',
  'Message-Id',
  'Date',
  'From',
  'Subject',
);

// define a variable to hold parsed headers
$headers = array();

// loop through data
foreach ($data as $data_line) {

  // for each line, assume a match does not exist yet
  $pattern_match_exists = false;

  // check for lines that start with white space
  // NOTE: if a line starts with a white space, it signifies a continuation of the previous header
  if ((substr($data_line,0,1)==' ' || substr($data_line,0,1)=="\t") && $last_match) {

    // append to last header
    $headers[$last_match][] = $data_line;
    continue;

  }

  // loop through patterns
  foreach ($patterns as $key => $pattern) {

    // create preg regex
    $preg_pattern = '/^' . $pattern .': (.*)$/';

    // execute preg
    preg_match($preg_pattern, $data_line, $matches);

    // check if preg matches exist
    if (count($matches)) {

      $headers[$pattern][] = $matches[1];
      $pattern_match_exists = true;
      $last_match = $pattern;

    }

  }

  // check if a pattern did not match for this line
  if (!$pattern_match_exists) {
    $headers['UNMATCHED'][] = $data_line;
  }

}

?>

編集

以下は、MailParse と呼ばれる PHP 拡張機能です。

http://pecl.php.net/package/mailparse

誰かが MimeMailParse と呼ばれるクラスを構築しました:

http://code.google.com/p/php-mime-mail-parser/

そして、ここにそれを使用する方法を議論するブログエントリがあります:

http://www.bucabay.com/web-development/a-php-mime-mail-parser-using-mailparse-extension/

于 2011-04-20T02:14:41.870 に答える