[PHP] Add an attachment on the fly to a Swift email

Published on 2018-10-16 • Modified on 2018-10-16

Because I always forget! 🤔


// Create attachment on the fly
$swiftAttachment = new \Swift_Attachment('ics data', 'mycalendar.ics', 'text/calendar');

$message = (new \Swift_Message())
    ->setSubject('Subject')
    ->setFrom('from@email.com')
    ->setTo('to@email.com')
    ->setCc('cc@email.com')
    ->setBcc('bcc@email.com')
    ->setReplyTo('replyto@email.com')
    ->setBody($body, 'text/html');

// Attach the file to the email message
$message->attach($swiftAttachment);

 More on Stackoverflow