Ilia Shakitko
Ilia Shakitko

Reputation: 1457

Attachment with file_get_contents?

I spent quite some time trying to figure out any cases with sending email using Lavarel 4 and including attachment to a message. Nobody even talking about it, everybody is attaching file from filesystem.

Did anybody have experience sending an email attaching an image (like this: http://www.w3schools.com/html/html5.gif) without actually downloading it on disk?

Upvotes: 1

Views: 5541

Answers (1)

jszobody
jszobody

Reputation: 28911

Swift Mailer definitely lets you attach data using Swift_Attachment::newInstance():

http://swiftmailer.org/docs/messages.html#attaching-dynamic-content

It appears Laravel has a wrapper method for this, it just isn't mentioned in the main documentation. See here:

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Mail/Message.php#L196

http://laravel.com/api/4.2/Illuminate/Mail/Message.html#method_attachData

So you'll use it like this:

$data = file_get_contents(...);
$message->attachData($data, $filename);

This is especially useful for cases when you are dynamically generating data yourself, like a PDF for instance.

If you are simply pulling in a pre-existing file from a URL, you can just use the standard attach() method with the URL, and let Swift Mailer fetch it:

$message->attach("http://www.w3schools.com/html/html5.gif");

Upvotes: 8

Related Questions