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

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

In this snippet, we create a mail attachment with the help of the Swift_Attachment object then we "attach" it to the Swift_Message instance.


// 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  Random snippet

  Work with me!