How do you attach a File (data object) to an email in 4.x?

silverstripe-4
Tags: #<Tag:0x00007f082706a000>

#1

Silverstripe Version:
4.3
Question:

In 4.x, it seems that you can no longer retrieve the absolute path to a file (sys path), but in Email::class, addAttachment function, it asks you for the path to file - so what should I do?

Cheers
Leo


#3

You can use the AddAttachmentFromData() method in the email class to avoid having to try and discover the paths. This will also mean that your code is compatible should you ever find yourself not using the local filesystem (SS4 abstracts all the file handling)

Assuming you have a file object:

$email->addAttachmentFromData($file->getString(), $file->Name, $file->getMimeType());

https://api.silverstripe.org/4/SilverStripe/Control/Email/Email.html#method_addAttachmentFromData


#2

OK, I’ve figured this myself:

return PUBLIC_PATH . $file->getSourceURL();

But this will require the file to be published first.

Cheers
Leo


#4

Cool! Thanks buddy, this is more decent :smiley: