通过电子邮件发送正文内容和日历邀请

时间:2019-08-21 15:09:31

标签: php sendgrid

我正在尝试发送包含日历邀请和HTML正文内容的电子邮件,但是我似乎无法将两者都添加到要通过SendGrid发送的电子邮件对象中

我能够单独发送日历邀请和HTML正文内容,但不能一起发送。

function sendgridAPI(){

GLOBAL $mgClient,$domain,$toName, $toEmail, $fromName, $fromEmail, $subj, $body, $cc, $bcc, $attachments, $mimeMessage, $sendgrid_api_key;


    $email = new \SendGrid\Mail\Mail();
    $email->setFrom($fromEmail, $fromName);
    $email->setSubject($subj);
    $toEmails = [$toEmail => $toName,];
    $email->addTos($toEmails);    



    if ($mimeMessage != ""){
        echo "<br> 1 <br>";

       $contents = [
        "text/calendar" => $mimeMessage,
        "text/html" => $body
        ];
        $email->addContents($contents);

    }
    else{
         $content = ["text/html" => $body];
         $email->addContent($content);
    }

    if($cc != ""){
        $ccEmails = [$cc => "CC",];
        $email->addCcs($ccEmails);     
    }

    if ($attachments != ""){
        $filePath = $attachments;
        $fileName = substr($attachments, strrpos($attachments, '/') + 1);
        $fileData = base64_encode(file_get_contents($filePath));
        $fileExtension = substr($attachments, strrpos($attachments, '.') + 1);
        $fileType = 'application/'. $fileExtension;

        $email->addAttachment(
            $fileData,
            $fileType,
            $fileName,
            "attachment"
        );
        $email->addAttachments($attachments);
    }


    $sendgrid = new \SendGrid($sendgrid_api_key);
    try {
        $response = $sendgrid->send($email);
        $data = $response->headers();
        print_r($data);
        gettype($data['5']);
        $responseSG = substr($data['5'], strpos($data['5'], ":") + 1);   
        return $responseSG;
        //echo $responseSG;
    } catch (Exception $e) {
        echo 'Caught exception: '. $e->getMessage() ."\n";
        return "";
    }
}
?>

将变量传递给此函数,然后构造电子邮件对象以使用SendGrid API发送

1 个答案:

答案 0 :(得分:1)

您需要为addAttachment()创建附件对象,而不要传递文件名。还有addAttachments()

的附件对象数组

https://github.com/sendgrid/sendgrid-php/blob/master/lib/mail/Mail.php#L1152-L1172

这是附件的构造函数:

https://github.com/sendgrid/sendgrid-php/blob/master/lib/mail/Attachment.php#L35-L52