php使用mandrillapp发送附件的方法

mandrillapp发送附件需要base64_encode源文件才可以

看代码:

$body = "";
$subject = "";
$attachments = array('');
$to = "";
$cc = "";
$bcc = "";
$from_email =""
$toArray =getToTypeArray($to,$cc,$bcc); 
$message = array(
        'html' => $body,
        'subject' => $subject,
        'from_email' => $from_email,
        'to' => $toArray
);

//合并数组
if(!empty($attachments)){
    $attachmentsArray = getAttachmentsArray($attachments);
    if(!empty($attachmentsArray['attachments'])){
        $message = array_merge($message,$attachmentsArray);
    }
}

try{
    $mandrill = new Mandrill('appkey');
    $async = false;
    $ip_pool = 'Main Pool';
    $send_at = date('Y-m-d H:i:s',time()-3600);
    $result = $mandrill->messages->send($message, $async, $ip_pool, $send_at);
    print_r($result);
}catch (Mandrill_Error $e){
    echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
    throw $e;
}


function getAttachmentsArray($attachments){
        $getAttachmentArray = array();
        $getAllAttachmentArray = array();
        foreach ($attachments as $attachment) {
            if (file_exists($attachment)) {
                $type = mime_content_type($attachment);
                $name = basename($attachment);
                $attachment_encoded = base64_encode(file_get_contents($attachment));
                $getAttachmentArray[] = array('type'=>$type,'name'=>$name,'content'=>$attachment_encoded);
            }
        }
        $getAllAttachmentArray['attachments'] = $getAttachmentArray;
        return $getAllAttachmentArray;
}


function getToTypeArray($to,$cc,$bcc){
    $getEmailArray = array();
    if (isset($to)) {
        $emails = explode(';', $to);
        foreach ($emails as $email) {
            $email = trim($email);
            if (!empty($email)) {
                $getEmailArray[] = array('email'=>$email, 'type' =>'to');
            }
        }
    }
    if (isset($cc)) {
        $emails = explode(';', $cc);
        foreach ($emails as $email) {
            $email = trim($email);
            if (!empty($email)) {
                    $getEmailArray[] = array('email'=>$email, 'type' =>'cc');
                }
            }
        }
    }

    if (isset($bcc)) {
        $emails = explode(';', $bcc);
        foreach ($emails as $email) {
            $email = trim($email);
            if (!empty($email)) {
                $getEmailArray[] = array('email'=>$email, 'type' =>'bcc');
            }
        }
    }    
    
    return $getEmailArray;
}
标签:

发表评论