ZendFramework-Zend_Mail-郵件

簡介

        Zend_Mail提供了通用化的功能來創作和發送文本以及兼容MIME標準的含有多個段的郵件消息。
        Zend_Mail通過php內建的mail()函數或者直接通過SMTP連接來發送郵件


使用Zend_Mail發送簡單郵件

        一個簡單郵件由一個或者幾個收件人,一個主題,一個郵件主體和一個發件人組成。
        下面的步驟,使用了PHP的mail()函數來發送郵件:

                <?php
                require_once 'Zend/Mail.php';
                $mail = new Zend_Mail();
                $mail->setBodyText('This is the text of the mail.');
                $mail->setFrom('[email protected]', 'Some Sender');
                $mail->addTo('[email protected]', 'Some Recipient');
                $mail->setSubject('TestSubject');
                $mail->send();
                ?>

        通過“get”方法可以讀取絕大多數儲存在“mail”對象中的郵件屬性,
        getRecipients()是一個特例,它返回一個含有所有先前被加入的收件人地址的數組。

        出於安全原因,Zend_Mail了過濾郵件頭中所有字段,
        以防止基於換行符(/n)郵件頭注入(header injection)漏洞攻擊


通過SMTP發送郵件

        以SMTP方式發送郵件,Zend_Mail_Transport_Smtp對象需要在send()方法被調用之前創建並註冊到Zend_Mail中去。
        當前腳本程序中所有使用Zend_Mail::send()發送的郵件,都將以SMTP方式傳送:

                <?php
                require_once 'Zend/Mail/Transport/Smtp.php';
                $tr = new Zend_Mail_Transport_Smtp('mail.example.com');
                Zend_Mail::setDefaultTransport($tr);
                ?>

        setDefaultTransport()方法的調用和Zend_Mail_Transport_Smtp對象的構造代價並不昂貴。
        這兩行可以添加在腳本程序的配置文件(例如config.inc或者類似文件)中,從而爲整個腳本程序配置Zend_Mail類的行爲。
        如此可以把配置信息從應用程序邏輯分離出來郵件是通過SMTP還是mail()發送,使用什麼郵件服務器等等。


通過一個SMTP連接發送多個郵件

        在缺省狀態下,系統會爲每一個被髮送的郵件建立一個SMTP連接。
        如果想通過一個SMTP連接發送多個郵件,可以自己調用connect()函數。
        如果在send()被調用之前就已經建立了一個傳送連接,那麼這個連接會被使用並且不會被自動關閉。

                <?php
                require_once 'Zend/Mail.php';
                $mail = new Zend_Mail();
                // build message...
                require_once 'Zend/Mail/Transport/Smtp.php';
                $tr = new Zend_Mail_Transport_Smtp('mail.example.com');
                Zend_Mail::setDefaultTransport($tr);
                $tr->connect();
                for ($i = 0; $i < 5; $i++) {
                $mail->send();
                }
                $tr->disconnect();
                ?>


使用不同的Transport對象

        有時想想使用不同的連接來發送不同的郵件,
        也可以不預先調用setDefaultTransport()方法,而直接將Transport對象傳遞給send()。
        被傳遞的transport對象會在實際的send()調用中替代缺省的transport:

                <?php
                require_once 'Zend/Mail.php';
                $mail = new Zend_Mail();
                // build message...
                require_once 'Zend/Mail/Transport/Smtp.php';
                $tr1 = new Zend_Mail_Transport_Smtp('[email protected]');
                $tr2 = new Zend_Mail_Transport_Smtp('[email protected]');
                $mail->send($tr1);
                $mail->send($tr2);
                $mail->send(); // use default again
                ?>
     
        外加transport,需要實現Zend_Mail_Transport_Interface接口。
     

HTML郵件

        發送HTML格式的郵件,使用setBodyHTML()方法來設置郵件正文而不是setBodyText()方法,
        MIME類型會被自動設置爲text/html。 如果既使用HTML又使用純文本,
        那麼multipart/alternative MIME類型的郵件消息將會自動產生:

        <?php
        require_once 'Zend/Mail.php';
        $mail = new Zend_Mail();
        $mail->setBodyText('My Nice Test Text');
        $mail->setBodyHtml('My Nice <b>Test</b> Text');
        $mail->setFrom('[email protected]', 'Some Sender');
        $mail->addTo('[email protected]', 'Some Recipient');
        $mail->setSubject('TestSubject');
        $mail->send();
        ?>


附件

        使用addAttachment()方法可以將文件附加到郵件中。
        Zend_Mail會缺省地認爲該文件是二進制對象(application/octet-stream),以 base64編碼傳輸,
        並且作爲郵件的附件處理。 通過傳遞額外的參數給addAttachment()方法可以覆蓋上述缺省設定:

                <?php
                require_once 'Zend/Mail.php';
                $mail = new Zend_Mail();
                // build message...
                $mail->addAttachment($someBinaryString);
                $mail->addAttachment($myImage, 'image/gif', Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_8BIT);
                ?>

        如果想得到對此附件MIME段產生的更多控制,可以使用addAttachment()方法的返回值來修改它的屬性。
        方法addAttachment()返回了一個Zend_Mime_Part對象:

                <?php
                require_once 'Zend/Mail.php';
                $mail = new Zend_Mail();

                $at = $mail->addAttachment($myImage);
                $at->type        = 'image/gif';
                $at->disposition = Zend_Mime::DISPOSITION_INLINE;
                $at->encoding    = Zend_Mime::ENCODING_8BIT;
                $at->filename    = 'test.gif';

                $mail->send();
                ?>


增加收件人

        有三種方法可以增加收件人:

                addTo():增加一個收件人到郵件頭“To”(收件人)

                addCc():增加一個收件人到郵件頭“Cc”(抄送)

                addBcc():增加一個收件人到郵件頭“Bcc”(暗送)
     
        addTo()和addCc()接受可選的第二個參數用於爲郵件頭的收件人指定具有可讀性的名字。


控制MIME分界線

        在一個包含多個段的郵件裏,用於分隔郵件不同段的MIME分界線(MIME boundary)通常是隨機生成的。
        但是在某些情況下,也許會希望使用特定的MIME分界線。
        如下面的例子所示,可以使用setMimeBoundary()方法來做到這一點:

                <?php
                require_once 'Zend/Mail.php';
                $mail = new Zend_Mail();
                $mail->setMimeBoundary('=_' . md5(microtime(1) . $someId++);
                // build message...
                ?>


外加郵件頭信息

        使用addHeader()方法可以外加任意的郵件頭信息。它需要兩個參數,頭信息的名稱和值,
        第三個可選的參數,它決定了該郵件頭信息是否可以有多個值:

                <?php
                require_once 'Zend/Mail.php';
                $mail = new Zend_Mail();
                $mail->addHeader('X-MailGenerator', 'MyCoolApplication');
                $mail->addHeader('X-greetingsTo', 'Mom', true); // multiple values
                $mail->addHeader('X-greetingsTo', 'Dad', true);
                ?>


字符集

        Zend_Mail不會對郵件段字符集的正確性進行檢查。 當Zend_Mail初始化的時候,
        缺省地爲郵件設置了iso8859-1字符集。
        程序必須確保添加至郵件對象的所有段都以正確的字符集編碼。
        在添加一個新的郵件段時,可以爲每個段指定不同的字符集。

        字符集只適用於文本格式中的段。


編碼

        文本和HTML信息在缺省下以Quoted-printable機制編碼。
        在調用addAttachment()方法添加附件的時候, 如果沒有指定編碼方式,都將以base64方式編碼,
        或稍後通過給MIME段對象(Zend_Mime_Part)相應屬性賦值來指定編碼方式。
        7Bit和8Bit編碼目前僅僅在二進制數據上可行。

        Zend_Mail_Transport_Smtp編碼行以一個點(.)或者兩個點(..)起始,以確保郵件不違反SMTP協議。


SMTP 身份驗證

        Zend_Mail 支持使用 SMTP 身份驗證,通過配置數組傳遞“auth”參數到 Zend_Mail_Transport_Smtp 的構造函數中。
        可用的內建身份驗證方法爲 PLAIN,LOGIN 和 CRAM-MD5,這些都需要在配置數組中設置“username”和“password”。

                <?php
                require_once 'Zend/Mail.php';
                require_once 'Zend/Mail/Transport/Smtp.php';

                $config = array('auth' => 'login',
                'username' => 'myusername',
                'password' => 'password');

                $transport = new Zend_Mail_Transport_Smtp('mail.server.com', $config);

                $mail = new Zend_Mail();
                $mail->setBodyText('This is the text of the mail.');
                $mail->setFrom('[email protected]', 'Some Sender');
                $mail->addTo('[email protected]', 'Some Recipient');
                $mail->setSubject('TestSubject');
                $mail->send($transport);
                ?>

        身份驗證的類型是大小寫不敏感的,但是不能有標點符號。
        例如,使用 CRAM-MD5 類型,則應當傳遞 'auth' => 'crammd5' 到 Zend_Mail_Transport_Smtp 的構造函數中。
     

Securing SMTP Transport 安全性

        Zend_Mail also supports the use of either TLS or SSL to secure a SMTP connection.
        This can be enabled be passing the 'ssl' parameter to the configuration array
        in the Zend_Mail_Transport_Smtp constructor with a value of either 'ssl' or 'tls'.
        A port can optionally be supplied, otherwise it defaults to 25 for TLS or 465 for SSL.

                <?php
                require_once 'Zend/Mail.php';
                require_once 'Zend/Mail/Transport/Smtp.php';

                $config = array('ssl' => 'tls',
                                'port' => 25); // Optional port number supplied

                $transport = new Zend_Mail_Transport_Smtp('mail.server.com', $config);

                $mail = new Zend_Mail();
                $mail->setBodyText('This is the text of the mail.');
                $mail->setFrom('[email protected]', 'Some Sender');
                $mail->addTo('[email protected]', 'Some Recipient');
                $mail->setSubject('TestSubject');
                $mail->send($transport);
                ?>


Reading Mail Messages 讀取郵件

        Zend_Mail can read mail messages from several local or remote mail storages.
        All of them have the same basic API to count and fetch messages
        and some of them implement additional interfaces for not so common features.
        For a feature overview of the implemented storages see the following table.

        Feature            Mbox        Maildir            Pop3        IMAP
        Storage type        local        local        remote        remote
        Fetch message        Yes            Yes            Yes            Yes
        Fetch mime-part            emulated        emulated        emulated        emulated
        Folders            Yes            Yes            No        Yes
        Create message/folder        No        todo        No        todo
        Flags        No        Yes            No        Yes

        Simple example using Pop3

                <?php
                $mail = new Zend_Mail_Storage_Pop3(array('host'     => 'localhost',
                                                        'user'     => 'test',
                                                        'password' => 'test'));

                echo $mail->countMessages() . " messages found/n";
                foreach ($mail as $message) {
                    echo "Mail from '{$message->from}': {$message->subject}/n";
                }
                ?>

                $mail = new Zend_Mail_Storage_Mbox(array('filename' => '/home/test/mail/inbox'));
                $mail = new Zend_Mail_Storage_Maildir(array('dirname' => '/home/test/mail/'));
                // connecting with Pop3
                $mail = new Zend_Mail_Storage_Pop3(array('host'     => 'example.com'
                                                        'user'     => 'test',
                                                        'password' => 'test'));

                // connecting with Imap
                $mail = new Zend_Mail_Storage_Imap(array('host'     => 'example.com'
                                                        'user'     => 'test',
                                                        'password' => 'test'));

                // example for a none standard port
                $mail = new Zend_Mail_Storage_Pop3(array('host'     => 'example.com',
                                                        'port'     => 1120
                                                        'user'     => 'test',
                                                        'password' => 'test'));


Advanced Use 高級應用

        Using NOOP
        Caching instances
        Extending Protocol Classes


實例

        // Send email
        $str_email_to = $this->arr_email_to[$arr_params['category']][$arr_params['issue']][$arr_params['paidUser']];
        $str_category = $this->arr_faq_info[$arr_params['category']];
        $str_issue = $this->arr_faq_info[$arr_params['issue']];        
        $arr_config = array(
                        'auth'     => 'login',
                        'username' => '[email protected]',
                        'password' => 'invite1234abcd'
                    );
        $transport = new Zend_Mail_Transport_Smtp('64.78.165.106', $arr_config);
        Zend_Mail::setDefaultTransport($transport);
        try {
            // Content
            $str_message = "Category: ". $str_category."/r/n <br/>";
            $str_message .= "The specific issue: ". $str_issue."/r/n <br/>";
            $str_message .= "Paid User: ". $arr_params['paidUser']."/r/n <br/>";
            $str_message .= "Subscriber: ". $str_subscriber."/r/n <br/>";
            $subject = 'FAQ';
            $obj_mail = new Zend_Mail();
            $obj_mail->setBodyHtml($str_message);          
            $obj_mail->setFrom($arr_config['username'], 'FAQ');
            $obj_mail->addTo($str_email_to, '');
            $obj_mail->setSubject($subject);
            try{
                $obj_mail->send($transport);
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章