I am trying to send an email via SendGrid/PHP with zip folder attached to email. the variable $attachments contains list of zip folders.
public static function send_mail($to = "info@example.co.za", $subject = "Testing", $templateId, $templateData = [], $attachments = [], $attachmentName = "testing.docx")
{
$email = new \SendGrid\Mail\Mail();
$email->setSubject($subject);
if (is_array($to)) {
foreach ($to as $key => $value) {
$email->addTo($value);
}
} else {
$email->addTo($to);
}
if ($templateData) $email->addDynamicTemplateDatas($templateData);
$email->setFrom(getenv("MAIL_FROM_ADDRESS"), getenv("MAIL_FROM_NAME"));
$email->setTemplateId($templateId);
$sendgrid = new \SendGrid(getenv("SENDGRID_API_KEY"));
if ($attachments && is_array($attachments)) {
foreach ($attachments as $key => $file) {
$attachment = new Attachment();
$content = file_get_contents($file["file"]);
$attachment->setContent($content);
$attachment->setType(Helper::setFileType($file["file"]));
$attachment->setFilename($file["name"] . "." . pathinfo($file["file"], PATHINFO_EXTENSION));
$attachment->setDisposition("attachment");
$email->addAttachment($attachment);
}
}
try {
$sendgrid->send($email);
} catch (Exception $e) {
print_r("Caught exception: " . $e->getMessage()) . "\n";
}
}
private static function setFileType($file): string
{
$type = pathinfo($file, PATHINFO_EXTENSION);
$types = [
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"pdf" => "application/pdf",
"zip" => "application/zip",
];
return $types[$type];
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire