Curs Php-mysql

- Definire continut email
- Exemplu trimitere Email
- Metodele queue() si later()

Laravel foloseste libraria "SwiftMailer" pentru trimitere email-uri, si clasa Mailable pt. definirea datelor de email.

Generare si scriere Mailables

In Laravel, datele de Email sunt construite in clase Mailables. Aceste clase sunt create in directorul app/Mail/ ( va fi generat cand creati prima clasa mailable).
- Ca sa creati automat o clasa mailable, folositi aceasta comanda in Command-Line-Interface:
php artisan make:mail ClassName
Clasa mailable contine o metoda build() in care se definesc configuratiile email-ului. In aceasta metoda puteti apela mai mute metode inlantuite, precum: from(), subject(), view(), attach().
public function build(){
  return $this->from('from_email@example.com', 'Some-Name')->subject('Mail Subject')->view('view_name');
}
- Daca adresa si numele pt. 'from' nu sunt specificate, Laravel va folosi Global "From" Address (definit in config/mail.php).

- Daca 'subject' nu e specificat, Laravel va folosi ca subiect un sir format din numele clasei, de exemplu: "User Mail".

Trimitere Mail

Pentru a trimite email, se foloseste aceasta sintaxa in aplicatia Laravel:
use App\Mail\MailableClass;
use Illuminate\Support\Facades\Mail;

//...
Mail::to('to_mail@example.com')->send(new MailableClass($data));
Puteti adauga recipiente "to", "cc", si "bcc" intr-o singura apelare inlantuita:
Mail::to('to_mail@example.com')
 ->cc('other_mail@example.com')
 ->bcc('another_mail@example.com')
 ->send(new MailableClass($data));

Definire continut email

Pentru a crea mesajul din email, folositi metoda view() in metoda build() din clasa mailable:
public function build(){
  return $this->view('view_name');
}
- "view_name" e numele view-ului cu template-ul pentru continutul email-ului.
Tempate-ul pentru email se constuieste si se incarca la fel ca oricare fisier "view", puteti folosi tag-uri HTML, cod PHP, sintaxa Blade si date pentru continut transmise la apelarea fisierului.
Exemplu de template blade simplu pt. continutul unui email:
<h1>Hi, {{ $name }}</h1>
<p>This is email content, sent with Laravel.</p>
Pentru a trimite un email cu text-simplu, se foloseste metoda text() in build():
public function build(){
  return $this->text('view_name');
}

Transmitere Date la View

Sunt doua modalitati de a transmite date in variabile la view-ul pt. email:

- Prin Proprietati ale clasei

Orice proprietate "public" definita in clasa mailable va fi automat valabila in view. Astfel puteti transmite date la constructor-ul clasei si sa le adaugati in proprietati publice ale clasei:
class ClassName extends Mailable {
  public $data; //array with data for mail content ['name'=>'abc', ...]

  public function __construct($data){
    $this->data = $data;
  }

  public function build(){
    return $this->view('view_name');
  }
}
Dupa ce datele sunt retinute in proprietati publice, pot fi preluate direct in view, prin numele proprietatii:
<h1>Hi, {{ $data['name'] }}</h1>
<p>What appears and disappears does not really exist.</p>

- Prin metoda with()

Un alt mod de a trimite date variabile la view e prin folosirea metodei with() in build().
- Daca transmiteti date la constructor-ul clasei mailable; adaugati acele date in proprietati protected sau private, apoi folositi-le in metoda with():
class ClassName extends Mailable {
  protected $data; //array with data for mail content ['name'=>'abc', ...]

  public function __construct($data){
    $this->data = $data;
  }

  public function build(){
    return $this->view('view_name')->with(['name'=>$this->data['name']);
  }
}
Apoi, in view:
<h1>Hi, {{ $name }}</h1>
<p> What a peaceful happy day.</p>

Adaugare atasamente in email

Ca sa adaugati fisiere atasate la email, se foloseste metoda attach() in metoda build().
public function build(){
  return $this->view('view_name')->attach('/path/to/file');
}

Adaugare Imagine in email

Ca sa adaugati o imagine in continutul email-ului, puteti folosi metoda $message->embed() in template-ul pt. email. Laravel face automat o variabila $message valabila in template pt. email.
Email content. Here is an image:

<img src="{{ $message->embed($path_to_file) }}">

Exemplu trimitere Email

Exemplu trimitere email cu Laravel printr-un cont de Gmail.

1. Mai intai e necesar sa adaugati datele de autentificare la contul dv. de Gmail in parametri din fisierul .env din Laravel.
MAIL_DRIVER = smtp
MAIL_HOST = smtp.gmail.com
MAIL_PORT = 587
MAIL_USERNAME = gmail_username@gmail.com
MAIL_PASSWORD = gmail_password
MAIL_ENCRYPTION = tls
2. Dupa ce ati adaugat datele in fisierul .env, executi comanda urmatoare in Command-Line-Interface pt. a reseta cache-ul.
php artisan config:cache
3. Acum, creati clasa mailable.
- Rulati urmatorul cod in Command-Line-Interface:
php artisan make:mail SendMail
- Apoi, porniti serverul php in Laravel ("php artisan serve").
Comanda "php artisan make:mail SendMail" va crea un fisier SendMail.php cu clasa Mailable, in directorul app/Mail/.
- Sau puteti crea manual acel fisier, cu codul dat mai jos.
4. Copiati urmatorul cod in fisierul app/Mail/SendMail.php:
<?php
namespace App\Mail;

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

class SendMail extends Mailable {
  use Queueable, SerializesModels;

  protected $data =''; //data with ['etype'=>'email-type', 'name'=>'name-added-in-view']

  //Create a new message instance
  //Receives array
  public function __construct($data){
    $this->data = $data;
  }

  //Build email message
  //return $this
  public function build(){
    $data =['name'=>$this->data['name']]; //data to pass to view

    //builds email according to $email value
    if($this->data['etype'] =='text'){
      return $this->subject('Laravel Basic Text Mail')->text('mails.mail')->with($data);
    }
    else if($this->data['etype'] =='html'){
      //as html, with specified from-data
      return $this->from('from_mail@gmail.com', 'No-One')->subject('HTML Testing Mail')->view('mails.mail')->with($data);
    }
    else if($this->data['etype'] =='attachment'){
      //image address to be embed in mail template
      $data['img'] ='https://coursesweb.net/php-mysql/laravel/laravel.png';

      return $this->subject('Testing Mail with Attachment')->view('mails.mail')
       ->attach('https://coursesweb.net/blog/dwl/prayer_the_art_of_believing.pdf')
       ->with($data);
    }
  }
}
5. Creem un controler numit MailController, care sa afiseze o pagina pt. trimitere email.
- Copiati urmatorul cod si salvati-l in "app/Http/Controllers/MailController.php" (adaugati adresa dv. de email la metoda Mail::to() din sendEmail()).
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Mail\SendMail;
use Illuminate\Support\Facades\Mail;

class MailController extends Controller {

  //responds to GET /sendmail
  //return view
  public function index(){
    return view('mails.index');
  }

  //responds to POST /sendmail
  //return void|string
  public function sendEmail(Request $request){
    //if 'etype' field received, and its value is: text, html, or attachment
    if($request->has('etype') && in_array($request->etype, ['text', 'html', 'attachment'])){
      $data =['etype'=>$request->etype, 'name'=>'SomeOne'];
      Mail::to('to_mail@example.com')->send(new SendMail($data));

      return 'Email Sent. Check your inbox';
    }
    else return 'Not Valid Request';
  }
}
6. Creati un direct "mails" in directory resources/views/.
- In directorul resources/views/mails/ creati un fisier index.blade.php, si copiati in el urmatorul cod:
<!doctype html>
<html lang="{{app()->getLocale()}}">
<head>
<meta charset="utf-8">
<title>Laravel E-Mail</title>
</head>
<body>
<h1>Send Emails</h1>
<form action='{{route("sendmail")}}' method='post' onsubmit='this["submit"].outerHTML="Sending the Email"'>
{{ csrf_field() }}
<strong>E-mail type:<strong> 
<select name='etype'>
 <option value='text'>As plain text</option>
 <option value='html'>As HTML</option>
 <option value='attachment'>With Attachment</option>
</select><br>
 <input type='submit' id='submit' value='Send' />
</form>
</body>
</html>
7. Acum creati template-ul pentru continutul din email.
- In directorul "resources/views/mails/" creati un fisier "mail.blade.php" cu acest continut:
<h1>Hi, {{ $name }}</h1>
<p>Sending Mail from Laravel.</p>

@isset($img)
<img src="{{ $message->embed($img) }}">
@endisset
8. Pt. Rutele de accesare in browser, adaugati aceste linii de cod in routes/web.php:
Route::get('/sendmail','MailController@index');
Route::name('sendmail')->post('/sendmail','MailController@sendEmail');
9. Accesati urmatoarea adresa in browser:
//localhost:8000/sendmail
- Va afisa continutul creat in "resources/views/mails/index.blade.php", o pagina ca in aceasta imagine:

Emails index page

10. Selectati tipul de email care vreti sa fie trimis, si apasati butonul "Send".
- Dupa ce email-ul e trimis, va afisa un mesaj ca acesta:
Email Sent. Check your inbox

Metodele queue() si later()

Trimiterea de email-uri maresc timpul de raspuns a unui mesaj catre utilizator, de aceea puteti folosi metoda queue() in loc de send(), ca sa trimita email-ul in mod separat care sa nu intarzie raspunsul catre utilizator:
Mail::to('to_mail@example.com')->queue(new MailableClass($data));

Amanare trimitere Email

Ca sa amanati trimiterea email-urilor, se foloseste metoda later().
Metoda later() primeste ca argument o instanta de tip DateTime care indica timpul cand sa trimita email-urile:
$when = Carbon\Carbon::now()->addMinutes(10); //to send after 10 minutes

Mail::to('to_mail@example.com')->later($when, new MailableClass($data));

Implementare ShouldQueue

Daca aveti mai multe clase mailable si vreti ca toate email-urile sa fie trimise fara a mari timpul de raspuns, puteti implementa ShouldQueue la definirea claselor.
Cu aceasta implementare, chiar daca aplicati metoda send(), email-ul va fi trimis ca si cum e aplicat queue():
use Illuminate\Contracts\Queue\ShouldQueue;

class ClassName extends Mailable implements ShouldQueue {
  //
}

- Documentatie: Laravel - Mail

Un Test simplu in fiecare zi

HTML
CSS
JavaScript
PHP-MySQL
Engleza
Spaniola
Care tag HTML5 defineste un text marcat, evidentiat?
<mark> <embed> <span>
<p>Cursuri graruite: <mark>MarPlo.net</mark> , jocuri, anime.</p>
Ce pseudo-clasa CSS defineste un stil la element cand mouse-ul e deasupra lui?
:focus :hover :active
a:hover {
  font-weight: bold;
  color: #00da01;
}
Clic pe functia ce returneaza un sir cu un numar rotunjit la x decimale.
toPrecision(x) toFixed(x) floor(x)
var num = 12.34567;
num = num.toFixed(2);
alert(num);       // 12.35
Indicati functia PHP care adauga continutul unui fisier intr-un array.
[) file() readfile()
$arr = file("a_file.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
var_export($arr);
Clic pe raspunsul potrivit la intrebarea: "What time is it?"
On the 7th of July 1996 It is a quarter to 5. Nice weather.
What time is it? It is a quarter to 5.
- Cat este ora? E 5 fara un sfert.
Indicati raspunsul potrivit la intrebarea: "¿Qué hora es?"
Hace buen tiempo. En el 7 de julio de 1996 Son las tres menos cuarto.
¿Qué hora es? Son las tres menos cuarto.
- Cat este ora? E 3 fara un sfert.
Trimitere Email - Laravel tutorial

Last accessed pages

  1. Parcurgere Array secvential si asociativ (1588)
  2. PHP OOP - Clase, Obiecte, constructor (5102)
  3. Scripturi JavaScript (3639)
  4. Download carti electronice si programe pentru Limba Engleza (43198)
  5. Titluri, Paragrafe, Un nou rand, Linie orizontala (32360)

Popular pages this month

  1. Cursuri si Tutoriale: Engleza, Spaniola, HTML, CSS, Php-Mysql, JavaScript, Ajax (767)
  2. Exercitii engleza - English Tests and exercises - Grammar (596)
  3. Prezentul simplu si continuu - Present Tense Simple and Continuous (587)
  4. Gramatica limbii engleze - Prezentare Generala (580)
  5. Prezentul simplu - Exercitii si teste incepatori (504)