Linux下mail发送邮件出错如何解决

309 阅读1分钟

1.源代码

?php
// 邮件类
class QMail
{
    public $subject = '';
    public $message = '';
    public $header  = '';
    public $to      = '';


    public function __construct($to = null, $subject = null, $message = null, $header = null)
    {/*{{{*/
        $this->subject = $subject;
        $this->message = $message;
        $this->header  = $header;
        $this->to      = $to;


        if ($header)
        {
            $this->header = $header;
        } else
        {
            $this->header  = 'MIME-Version: 1.0' . "\r\n";
            $this->header .= 'Content-type: text/html; charset=utf8' . "\r\n";
            $this->header .= 'Content-Transfer-Encoding: base64' . "\r\n";
            $this->header .= 'From: xxx <xxx@example.com>' . "\r\n";
        }
    }/*}}}*/


    public function setSubject($subject)
    {/*{{{*/
        $this->subject = $subject;
    }/*}}}*/

    public function setMessage($message)
    {/*{{{*/
        $this->message = $message;
    }/*}}}*/


    public function appendMessage($message)
    {/*{{{*/
        $this->message .= $message;
    }/*}}}*/


    public function setHeader($header)
    {/*{{{*/
        $this->header = $header;
    }/*}}}*/


    public function setTo($to)
    {/*{{{*/
        $this->to = $to;
    }/*}}}*/


    public function addToMailList($email)
    {/*{{{*/
        $this->to .= ';' . $email;
    }/*}}}*/

    public function send()
    {/*{{{*/
        $subject = self::encodeSubject($this->subject);
        $retval = mail($this->to, $subject,  chunk_split(base64_encode($this->message)), $this->header);
        return $retval;
    }/*}}}*/


    public static function encodeSubject($subject)
    {/*{{{*/
        return "=?UTF-8?B?".base64_encode($subject)."?=";
    }/*}}}*/
}

// 发邮件方法
function sendEmail($title, $body)
{
    // 收件人
    $email = implode(';', array('xxx@example.com','xxx@example.com'));
    $mail = new QMail($email, $title, $body);
    $mail->send();
}

$ret = sendEmail('广告系统', '广告系统有一条广告待审核!');
var_dump($ret);
die;

2 测试步骤

2.1 执行该文件

> php mail.php

返回结果如下:

sendmail: warning: inet_protocols: IPv6 support is disabled: Address family not supported by protocol
sendmail: warning: inet_protocols: configuring for IPv4 support only
postdrop: warning: inet_protocols: IPv6 support is disabled: Address family not supported by protocol
postdrop: warning: inet_protocols: configuring for IPv4 support only

2.2 查询资料找到解决办法

PS.博客地址(blog.csdn.net/u012724167/…)

(1)查看当前的inet_protocols

> /usr/sbin/postconf | grep inet_protocols 

结果如下:

inet_protocols = all

(2) 修改postfix配置文件

> sudo vim /etc/postfix/main.cf
> 将 inet_protocols = all 改为inet_protocols = ipv4

(3) 重启postfix

/etc/init.d/postfix restart

2.3 重新执行mail.php文件

> php mail.php

结果正常