Laravel 5.4 - Send e-mail with text attached?

Asked

Viewed 1,087 times

1

The case is simple: I need to generate a text on Laravel based on Array and then attach this text file with Attachments via Mail::to()!

  • what is the array ???

1 answer

2


Step by step create a text file and send via email to is:

Step 1:

First thing is to configure the Filesystem of the briefcase storage with the command:

php artisan storage:link

this will create a folder inside the folder public, which is a way to organize your folders in the and put your files inside it, example:

inserir a descrição da imagem aqui

is inside that folder that will be saved the created files .txt from any arrayof .


Step 2:

Now is create a text file (.txt) with some values of a array, example:

$array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

$t = "";
foreach ($array as $i)
{
    $t .= $i . PHP_EOL;
}

and right after to save to folder storage the text file do:

\Illuminate\Support\Facades\Storage::disk('public')->put('400.txt', $t);

note that the Facade Storage has a disk by the name of public which is the configuration contained in app\config\filesystems.php

'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

this setting is responsible for telling the storage location that is the same as the link folder created storage, and do not worry that comes configured.

The method put finally creates a text file with the data from array which are now contained in the variable $t.

Step 3:

Type in the command line:

php artisan make:mail MailTxt

a class and configuration is created for sending the email, follows:

<?php namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class MailTxt extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct()
    {
        //
    }
    public function build()
    {
        return $this->view('email_txt')
                ->from('[email protected]')
                ->attach(public_path('/storage/400.txt'));
    }
}

that within the method build() let’s configure the following methods:

  • view: view name which is the main layout of your email
  • from: who is sending the email would be the email address
  • attach: the text file that was created earlier that will be attached

with these 3 steps an e-mail with the text attachment.

Complete code:

$array = [
  1,2,3,4,5,6,7,8,9,10,
  11,12,13,14,15,16,17,18,19,20
];

$t = "";
foreach ($array as $i)
{
    $t .= $i . PHP_EOL;
}

\Illuminate\Support\Facades\Storage::disk('public')->put('400.txt', $t);

\Illuminate\Support\Facades\Mail::to("[email protected]")->send(new \App\Mail\MailTxt());

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.