2012-02-05 62 views
3

我想轉發我反彈的電子郵件到一個PHP腳本來處理它們。我在用。用php腳本收集TO字段的電子郵件管道?

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

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

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

    // empty vars 
    $from = ""; 
    $subject = ""; 
    $headers = ""; 
    $message = ""; 
    $splittingheaders = true; 

    for ($i=0; $i < count($lines); $i++) { 
    if ($splittingheaders) { 
    // this is a header 
    $headers .= $lines[$i]."\n"; 

    // look out for special headers 
    if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) { 
     $subject = $matches[1]; 
    } 
    if (preg_match("/^From: (.*)/", $lines[$i], $matches)) { 
     $from = $matches[1]; 
    } 
} else { 
    // not a header, but message 
    $message .= $lines[$i]."\n"; 
} 

if (trim($lines[$i])=="") { 
    // empty line, header section has ended 
    $splittingheaders = false; 
    } 
    } 

    ?>  

完美的作品!但是,如何收集退回郵件中的「收件人」字段?我試着添加一個$ to變量,但它不起作用。

任何幫助將是巨大的,

感謝,

編輯:其實我需要得到消息的正文中的「收件人」字段。 - 它彈回的電子郵件。我如何拆開消息的主體以獲取特定信息?我應該使用該人的電子郵件創建一個特殊的標題,以便獲取此信息更容易?

+0

你需要知道它在消息體中的外觀,然後用正則表達式來獲取它。 – Alasdair 2012-02-05 09:55:26

+0

有時更可靠的另一種選擇是發送具有唯一返回路徑的每條消息。通過這種方式,您可以根據消息被反彈到的電子郵件地址確切地知道哪些消息會返回給您。 – 2012-02-06 09:27:48

回答

1

如果您可以創建自定義標題,那將是最簡單的。否則,您需要針對您的整個身體進行特定模式的匹配;如果你的身體文字可能有所不同,可能很難確保你總是匹配正確的文本。

自定義頁眉應該X-開始,所以也許這樣做:

if (preg_match("/^X-Originally-To: (.*)/", $lines[$i], $matches)) { 
    $originallyto = $matches[1]; 
} 

但隨着X-頭,他們是非標準的,所以最好選一個名字要麼是

  1. 通常只用於同一目的,或者
  2. 不可能被任何人在任何
使用

你應該注意的另一件事;消息中的行應始終以「\ r \ n」結尾,因此您可能希望在兩個字符(而不是「\ n」)上進行拆分以確保更一致的行爲。