2017-07-05 39 views
0

我有一个简单的SendGrid API设置,但我想知道如何在发送的电子邮件中包含附件。我将附件URL传递给$ _POST变量,因此可以返回完整路径,但不确定将它包含在我的设置中。带附件的SendGrid(PHP库)

// 
$i = 1; foreach ($cart as $download) { 

    $file . $i = $download['download']; 
    $file_encoded . $i = base64_encode(file_get_contents($file)); 
    $attachment . $i = new SendGrid\Attachment(); 
    $attachment . $i->setContent($file_encoded); 
    $attachment . $i->setType("application/zip"); 
    $attachment . $i->setDisposition("attachment"); 
    $attachment . $i->setFilename("test.zip"); 
    $mail->addAttachment($attachment . $i); 

    i++; 

} 

// Set email confirmation settings 
$email_subject = 'New order from ' . $user_details['first-name-billing'] . ' ' . $user_details['last-name-billing'] . ' via www.***.com'; 
$email_admin = '******@***.com'; // Client 
$email_customer = $user_details['email']; 

ob_start(); 
    require_once './email-confirmation.php'; 
    $email_body = ob_get_contents(); 
ob_end_clean(); 

// Send to confirmation to admin 
if ($email_admin) { 
    send_email($email_admin, $email_admin, $email_subject, $email_body); 
} 

// Send confirmation to customer 
if ($email_customer) { 
    send_email($email_admin, $email_customer, $email_subject, $email_body); 
} 

// SendGrid init 
function send_email($from_email, $to_email, $subject, $body) { 
    global $sgAPIKey; 
    $from = new SendGrid\Email(null, $from_email); 
    $to = new SendGrid\Email(null, $to_email); 
    $content = new SendGrid\Content("text/html", $body); 
    $mail = new SendGrid\Mail($from, $subject, $to, $content); 
    $sg = new \SendGrid($sgAPIKey); 
    $response = $sg->client->mail()->send()->post($mail); 
} 

回答

2

使用SendGrid\Attachment类。一个完整的例子可以在documentation

$filename = basename($url); 
$file_encoded = base64_encode(file_get_contents($url)); 
$attachment = new SendGrid\Attachment(); 
$attachment->setType("application/text"); 
$attachment->setDisposition("attachment"); 
$attachment->setFilename($filename); 
$mail->addAttachment($attachment); 
+0

谢谢!完善。我找不到这个。你知道是否有可能发送多个附件? –

+1

只需多次调用'addAttachment()'。 – Barmar

+0

我只是困惑,因为我已经建立了每个下载'$ downloads'的url数组,但是不认为我可以在我的send_mail函数中循环这个... –