天天看點

H5頁面生成word檔案及發送郵件

最近工作中有用到生成word文檔及發送該附件的郵件。先說說我的思路和流程吧;

1.在背景用PHP将資料組合拼接成HTML格式;

2.生成帶資料(HTML)的word文檔(生成到項目對應的目錄下);

3.配置發送郵件的資訊(如郵件的host/port/username等);

第一步:我們先将資料組裝拼接成HTML格式  代碼如下:

    header("Cache-Control: no-cache, must-revalidate");

    header("Pragma: no-cache");

    //有了這些,可以把帶html标簽的html源碼導入到word裡,并且可以保持html的樣式。

    $wordStr = '<html xmlns:o="urn:schemas-microsoft-com:office:office"xmlns:w="urn:schemas-microsoftcom:office:word" xmlns="http://www.w3.org/TR/REC-html40">

    <head>

    </head><body>';

    $wordStr .= '<div class="print-container"><div class="print-header"><h1>家訪記錄彙總</h1></div><div class="print-content">';

    for($i=1;$i<=14;$i++){

         $wordStr .= $this->getWordContent($i,$roomid); //拼接資料

    }

    $wordStr .= '</div></div>';

    $wordStr .= '</body></html>';

第2步.生成word檔案到項目對應的目錄下;

    $file = rand(10000000,99999999).'.docx';

    //儲存檔案到目錄

    $savefile = $file;

    $attachDir = C("resourceFilesUpload");//上傳檔案儲存路徑,結尾不要帶/

    $attachDir_show = C("resourceFilesView");

    $attachSubDir = 'visitdoc_'.date('ymd');

    $attachDir = $attachDir.'/'.$attachSubDir;

    if(!is_dir($attachDir))

    {

        @mkdir($attachDir, 0777);

    }

    $tempPath = $attachDir.'/'.$savefile;

    file_put_contents($tempPath,file_get_contents("php://input"));

    $myfile = fopen($tempPath, "a");

    fwrite($myfile, $wordStr);//寫入内容

    fclose($myfile);//關閉該操作

3.配置發送郵件的資訊(如郵件的host/port/username等);

     //擷取儲存檔案後的位址

    $fileurl = $_SERVER["DOCUMENT_ROOT"]."/Public/upload/".$attachSubDir.'/'.$savefile;

    //注意這裡不能用網絡位址 如www.baidu.com/image/xxx.jpg

    //郵件title

    $emaildesc = "您好:<br/>";

    $emaildesc .= "<b>家訪記錄彙總, 請打開附件檢視</b><br/>";

    $emaildesc .= "此緻,曉黑闆";

    //引用郵件發送類

    require THINK_PATH.'Extend/Emailsend/MySendMailNew.php';

    $mail = new MySendMailNew();

    $mail->setServer($this->emailhost, $this->username, $this->password); //你的郵件配置

    $mail->setFrom($this->fromemail);

    $mail->setReceiver($email);

    $mail->setMailInfo($fileName, $emaildesc, $fileurl);

    $mail->sendMail();

    //$this->success("郵件發送成功,請及時打開郵箱檢視");

    return true;

效果如下:

1.生成的word檔案

H5頁面生成word檔案及發送郵件

2.郵件發送後效果:

H5頁面生成word檔案及發送郵件

郵寄發送類的代碼見下面附件

繼續閱讀