【问题标题】:working with Email headers - PHP使用电子邮件标题 - PHP
【发布时间】:2012-09-17 11:58:59
【问题描述】:

我正在将收到的电子邮件传送到 handler.php。我可以成功地通过管道传输它并且它正在工作,但是当它从邮件标题中取出变量时,例如“主题”或“收件人”或“邮件正文”,我遇到了一些问题。这是我从here得到的代码

代码如下:

 <?php
//Assumes $email contains the contents of the e-mail
//When the script is done, $subject, $to, $message, and $from all contain appropriate values

//Parse "subject"
$subject1 = explode ("\nSubject: ", $email);
$subject2 = explode ("\n", $subject1[1]);
$subject = $subject2[0];

//Parse "to"
$to1 = explode ("\nTo: ", $email);
$to2 = explode ("\n", $to1[1]);
$to = str_replace ('>', '', str_replace('<', '', $to2[0]));

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

$start = count ($message1) - 3;

if ($start < 1)
{
    $start = 1;
}

//Parse "message"
$message2 = explode ("\n\n", $message1[$start]);
$message = $message2[0];

//Parse "from"
$from1 = explode ("\nFrom: ", $email);
$from2 = explode ("\n", $from1[1]);

if(strpos ($from2[0], '<') !== false)
{
    $from3 = explode ('<', $from2[0]);
    $from4 = explode ('>', $from3[1]);
    $from = $from4[0];
}
else
{
    $from = $from2[0];
}
?> 

对于 Gmail 电子邮件,它可以很好地获取主题、发件人、收件人和邮件正文,但它不适用于来自 Yahoo 的传入电子邮件。

是否有与所有著名电子邮件服务提供商兼容的通用 php 类?如果有人从 RoundCube 或其他电子邮件发件人发送电子邮件怎么办?如何成功检测变量?

谢谢!

【问题讨论】:

  • 电子邮件标题应该是标准的。您需要查看来自 Yahoo 和其他无效的电子邮件,并尝试了解其中的区别。从Subject: 之后的缺失空格到区分大小写的问题,都可能是这样。标题应该足够相似,如果你能找到一些错误,它将适用于所有电子邮件。恐怕我不能推荐一个包罗万象的图书馆
  • @Basic 没那么简单!例如,上面的代码将在电子邮件正文中包含此文本(来自 Yahoo)“--1375426159-60184550-1348612182=:61766 Content-Type: text/html; charset=us-ascii”,我应该怎么做检查所有电子邮件客户端? WHMCS/Kayako 支持这样的网络应用程序是如何工作的?这应该很有趣!

标签: php email-headers


【解决方案1】:

如果您需要一些非常简单的东西,这是一个起点:

list($headers, $message) = explode("\n\n", $email);

$header = imap_rfc822_parse_headers($headers);

// You can now access
$header->from;
$header->to;
$header->subject;

电子邮件部分(即使单独使用)也可以使用imap_rfc822_parse_adrlist() 进行解析。

【讨论】:

    【解决方案2】:

    您在 cmets 中描述的消息格式是 Multi-Part Mime 编码。

    有很多事情需要考虑 - 如果电子邮件是 HTML 纯文本格式,并且包含嵌入的图像、附件等,该怎么办?

    如果您使用的 PHP 版本是使用 MailParse 扩展构建的,那么它们应该为您提供一组相当简单的工具供您使用。

    Google 代码上还有 Mime Email Parser 可用,我以前没有使用过,但看起来相当简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-21
      • 2013-01-02
      • 2019-04-28
      • 2012-03-20
      • 2012-12-05
      • 2021-11-06
      • 1970-01-01
      • 2015-04-29
      相关资源
      最近更新 更多