通过电子邮件发送现有的多个文件附件。智者/ PHP

时间:2016-04-13 14:41:58

标签: php smarty phpmailer

我需要发送数据库中存在的多个文件附件,此代码只能发送一个文件(从循环中选择任何一个)。但我需要发送的不仅仅是存档。请帮帮我这件事,我真的很感激。请问我什么。谢谢。

//////////表格页

<form novalidate="novalidate" action="{$CMS_base_url}admin/employee_view_email.php?id={$id}" method="post" enctype="multipart/form-data">
    <input type="hidden" id="id" name="id" value="{$id}" />

    {if is_array ($cvs) && $cvs != "" }
        <table class="table table-hover">
            <thead>
                <tr>
                    <th class="col-md-2">Create date</th>
                    <th class="col-md-7">Document name / Description</th>
                    <th class="col-md-3">Select All <input type="checkbox" name="all" id="all" value="1" onclick="checkUncheckAll(this);" /></th>
                    <th class="col-md-3">Download</th>
                </tr>
            </thead>
            <tbody>

            {foreach from=$cvs key=k item=i}
                <tr>
                    <td><em>{$i.createdAt}</em></td>
                        <td><strong>{$i.title}</a></strong></td>
                        <td><input type="checkbox" name="txt_existed_cv_attach" id="txt_existed_cv_attach" value="{$i.id}" /></td>
                        <td><a href="{$CMS_base_url}admin/employee_cv_download.php?id={$i.id}&amp;u_id={$i.employee_id}">Download</a></td>
                </tr>
            {/foreach}
            {else}
                <tr>
                    <td>{lang mkey='error' skey='noResult'}</td>
                    <td>Upload a new document to send by Admin Email  {lang mkey='info' skey='fileAttachments'}</td>
                    <td colspan="2"><input class="btn-u btn-u-dark-blue" type="file" name="txt_cv_attach" id="txt_cv_attach" multiple="multiple"></td>
                </tr>
            </tbody>
        {/if}
            </table>

    <input type="submit" name="bt_send_atach" value="SEND EMAIL TO ADMIN" class="btn-u btn-u-lg btn-u-dark-blue pull-left" />
</form>

////////// PAGE for fetching('admin / employeeView.tpl')FORM PAGE

$id = (int)$_GET['id'];
$smarty->assign('id', $id );
$employee = Employee::find_by_id( $id );

require (CMS_LIB_PATH.DS.'class.cv.php');

///... more classes for employee/user to fetching the related page

$cvs = CV::manageEmployeeCV( $id );
if ( is_array($cvs) and !empty($cvs) )
{
    $temp = array();
    $i=1;
    foreach( $cvs as $cv )
    {
        $showTo = lang('select','cvShowType');

        $temp[$i]['id']             = $cv->id;

        $temp[$i]['name']           = $cv->originalName;
        $temp[$i]['type']           = $cv->fileType;
        $temp[$i]['tmp_name']       = CMS_SITE_ROOT.DS.'curriculum_vitae_file'.DS.$cv->fileName;
        $temp[$i]['error']          = 0;
        $temp[$i]['size']           = $cv->fileSize;

        $temp[$i]['title']          = $cv->title;
        $temp[$i]['description']    = $cv->description;
        $temp[$i]['showTo']         = $showTo[$cv->showTo];
        $temp[$i]['defaultCV']      = $cv->defaultCV;
        $temp[$i]['createdAt']      = strftime(dateFormat, strtotime($cv->createdAt) );
        $temp[$i]['modifyAt']       = strftime(dateFormat, strtotime($cv->modifyAt) );
        $temp[$i]['noViews']        = $cv->noViews;
        $temp[$i]['employee_id']    = $cv->employeeIDFK;
        $i++;
    }
    $smarty->assign( 'cvs', $temp );

}

$smarty->assign('employee', $employee );
$smarty->assign('lang', $lang);
$smarty->assign( 'message', $session->getMessage() );
$smarty->assign('rendered_page', $smarty->fetch('admin/employeeView.tpl') );
$smarty->display('admin/index.tpl');
$session->unsetMessage();

////////// CLASS.CV.PHP PAGE with DATABASE QUERY FOR LINE

public static function getCVByEmployee( $id=0, $employee_id=0 )
    {
        global $database, $db;
        $sql = " SELECT * FROM ". self::$table_name;
        $sql .= " WHERE id=".$db->escape_value($id)." AND employeeIDFK=".(int)$employee_id;
        $sql .= " LIMIT 1 ";
        $result = self::find_by_sql( $sql );
        return !empty($result) ? array_shift($result) : false;
    }

//。$ db-&gt; escape_value($ id)。 //其他包含更多数据库类的页面

public function escape_value ( $string ){
        if( $this->mysqli_real_escape_string ){
            if($this->magic_quotes_active){ $string=stripslashes($string); }
            $string = mysqli_real_escape_string($this->connection, $string);
        }else{
            if(!$this->magic_quotes_active){ $string= addslashes($string); }
        }
        return $string;
    }

//////////电子邮件处理页面..... admin / employee_view_email.php?id = {$ id}

$id = (int)$_GET['id'];
$smarty->assign('id', $id );
$employee = Employee::find_by_id( $id );

///... more classes for employee/user data to send my email

include_once CMS_LIB_PATH.DS.'class.cv.php';

$cvFile = $_FILES['txt_cv_attach'];
$cv_already_existed = $_POST['txt_existed_cv_attach'];

if($cv_already_existed != '' )
{

        include_once CMS_LIB_PATH.DS.'class.cv.php';
        $cvFile = array();
        $user_id = $session->getUserID();
        $cv_f = CV::getCVByEmployee( $cv_already_existed, $id );

        $cvFile['name']     = $cv_f->originalName;
        $cvFile['type']     = $cv_f->fileType;
        $cvFile['tmp_name'] = CMS_SITE_ROOT.DS.'curriculum_vitae_file'.DS.$cv_f->fileName;
        $cvFile['error']    = 0;
        $cvFile['size']     = $cv_f->fileSize;

}
else
{
/*
    * check for upload file
*/
    if( $cvFile['error'] == 4 )
    {
        $errors[] = lang( 'error', 'noCVFileApplication');
    }

    if( $cvFile['error'] == 0 )
    {
            $ext = end(explode(".", basename($cvFile['name']) ));
            $ext = strtolower($ext);
            if( !in_array($ext, $allowed_files) )
            {
                $e = lang('error', 'fileNotAllowed');
                $e = str_replace('@file_name@', basename($cvFile['name']) , $e );
                $errors[] = $e;
            }

            if($cvFile['size'] > max_upload_cv_size )
            {
                $errors[] = lang('error', 'max_file_size');
            }

    }
}


if( $employee)
{
    $full_name = $employee->full_name();
    $from   = array("email" => no_reply_email, "name" => $full_name );

    include CMS_LANGUAGE.DS.'emailTemplate.php';
    //send email to admin
            $to     = array("email" => notify_email, "name" => site_name );
            $emailTemplate = lang('email_template','notify_candidate_view_email');
            $subject = $emailTemplate['subject'];

            $body = $emailTemplate['body'];
            $body = str_replace( "@full_name@", $full_name , $body );
            $body = str_replace( "@firstName@", $employee->firstName , $body );
            $body = str_replace( "@middleName@", $employee->middleName, $body );
            $body = str_replace( "@surname@", $employee->surname, $body );
            $body = str_replace( "@address@", $employee->address, $body );
            $body = str_replace( "@cv_title@", $cv_f->originalName, $body );
            $body = str_replace( "@cv_type@", $cv_f->fileType, $body );     
            $body = str_replace( "@user_id@", $user_id , $body );

            $emailBody= array('html' => $body, 'plain' => $body );
            $mail = sendMail( $from, $to, $subject, $emailBody, $cvFile);

    unset( $_SESSION['account'] );
    $message = '<div class="alert success">'.lang('success','email_send_to_admin').'</div>';
}
else
{
    $message = lang( 'error', 'errorHead' );
    $message .= "<ul> <li />";
    $message .= join(" <li /> ", $employee->errors );
    $message .= "</ul>";
    $message = "<div class='alert error'>".$message."</div>";
}

$smarty->assign( 'cvs', $temp );
$smarty->assign('employee', $employee );
$smarty->assign('lang', $lang);
$session->setMessage( $message );
redirect_to( CMS_BASE_URL . 'admin/employee_view.php?id='.$id );
exit;

//////////发送电子邮件分类页

function sendMail( $from='', $to='', $subject='', $message='', $cvFile='', $clFile='' )
{
    global $smarty;
    if( $cvFile || !empty($cvFile) || is_array($cvFile) )
    {
            $CV_temp_path  = $cvFile['tmp_name'];
            $CV_filename   = basename($cvFile['name']);
            $CV_type       = $cvFile['type'];
            $CV_size       = $cvFile['size'];
    }

    if( mail_type == 1 )
    {

        $mail->IsSMTP();
        $mail->Host       = "ukm3.siteground.biz";
        $mail->Port       = "465";
        $mail->SMTPSecure = "ssl";
        $mail->SMTPAuth   = true;
        $mail->Username   = "admin username";
        $mail->Password   = "password";
    }

    try {
        $mail->AddAddress($to_email, $to_name);
        $mail->SetFrom($from_email, $from_name); //email, name
        $mail->Sender=$from_email;

        $mail->Subject = $subject;
        $mail->AltBody = $plain;
        $mail->MsgHTML($html);

        if( !empty($cvFile) && is_array($cvFile) && !empty($CV_filename) )
        {
            $mail->AddAttachment($CV_temp_path, $CV_filename, "base64", $CV_type); // attachment
        }

        return $mail->Send();
    }

    catch (phpmailerException $e)
    {
        echo $e->errorMessage(); //error messages from PHPMailer
        die;
    }

    catch (Exception $e) 
    {
        echo $e->getMessage(); //error messages from anything else!
        die;
    }
}

1 个答案:

答案 0 :(得分:0)

很难判断你的所有代码(也因为包含了我不知道的内容),但看起来这就是问题所在:

  if( !empty($cvFile) && is_array($cvFile) && !empty($CV_filename) )
    {
        $mail->AddAttachment($CV_temp_path, $CV_filename, "base64", $CV_type); // attachment
    }

您想要添加多个附件,而不是1。

你给数组$ cvFile(命名不好。将它命名为$ cvFileArr以使其清楚。现在它看起来像一个名称/路径。)

所以我希望你需要对这些值进行一些循环,比如这样(未经测试):

if( !empty($cvFile) && is_array($cvFile) && !empty($CV_filename) ) {
  foreach($cvFile as $oneFile){
        $mail->AddAttachment($CV_temp_path, $oneFile, "base64", $CV_type); // attachment
  }
}

但很难确切地说出来。但我希望您需要为每个文件添加$ mail-&gt; AddAttachment。