Laravel Course

- Defining email content
- Example Sending Email
- Queueing Email

Laravel uses the "SwiftMailer" library to send emails, and Mailable class to define email data.

Generating and Writing Mailables

In Laravel, Email data are build in Mailables classes. These classes are stored in the app/Mail/ directory (it will be generated when you create your first mailable class).
- To create a mailable class, use this command in Command-Line-Interface:
php artisan make:mail ClassName
The mailable class contains a build() method, in which mail configurations are defined. Within this method, you may call various methods such as from(), subject(), view(), attach().
public function build(){
  return $this->from('from_email@example.com', 'Some-Name')->subject('Mail Subject')->view('view_name');
}
- If the from address and name aren't specified, Laravel will use the Global "From" Address (defined in config/mail.php).

- If the subject isn't specified, Laravel will guess it from your class name, for example "User Mail".

Sending Mail

To send the email, use this syntax in your Laravel application:
use App\Mail\MailableClass;
use Illuminate\Support\Facades\Mail;

//...
Mail::to('to_mail@example.com')->send(new MailableClass($data));
You may set "to", "cc", and "bcc" recipients within a single, chained method call:
Mail::to('to_mail@example.com')
 ->cc('other_mail@example.com')
 ->bcc('another_mail@example.com')
 ->send(new MailableClass($data));

Defining email content

To build the e-mail message, use the view() method within the build() method of the mailable class:
public function build(){
  return $this->view('view_name');
}
- "view_name" is the name of the view that contains the template for email content.
The e-mail templates are loaded in the same way as views, you can use HTML tags, PHP code, Blade syntax and inject data into your email content.
For example, a simple blade template for email content:
<h1>Hi, {{ $name }}</h1>
<p>This is email content, sent with Laravel.</p>
To send a plain-text email, use the text() method in build():
public function build(){
  return $this->text('view_name');
}

Passing Data to View

There are two ways to pass data to the view for email content:

- Via Public Properties

Any public property defined on your mailable class will automatically be made available to the view. So, you may pass data into your mailable class' constructor and set that data to public properties defined on the class:
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');
  }
}
Once the data has been set to a public property, it will automatically be available in your view:
<h1>Hi, {{ $data['name'] }}</h1>
<p>What appears and disappears does not really exist.</p>

- Via the with() method

Another way to pass data into the view is to use the with() method in build().
- If you will pass data via the mailable class' constructor; set this data to protected or private properties, then use it in the with() method:
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']);
  }
}
Then, in your view:
<h1>Hi, {{ $name }}</h1>
<p> What a peaceful happy day.</p>

Attachments

To add attachments to an email, use the attach() method within the build() method.
public function build(){
  return $this->view('view_name')->attach('/path/to/file');
}

Embedding Image in email

To embed an inline image, use the $message->embed() method within your email template. Laravel automatically makes the $message variable available to all of your email templates.
Email content. Here is an image:

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

Example Sending Email

Here is an example of sending email with Gmail account.

1. First, you need to configure your Gmail account in Laravel .env file by changing the .env parameters as shown below.
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. After changing the .env file, execute the below command in Command-Line-Interface to clear the cache.
php artisan config:cache
3. Now, we create the mailable class.
- Run the following code in Command-Line-Interface:
php artisan make:mail SendMail
- Then, restart the Laravel server.
The command above will create a SendMail.php file with a Mailable class, in app/Mail/ directory.
You can also create manually this file with the code presented below.
4. Copy the following code in the app/Mail/SendMail.php file:
<?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/addons/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. We create a controller called MailController, to display the page and to send the email.
- Copy the following code and save it in "app/Http/Controllers/MailController.php" (add your email address to the Mail::to() method in 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. Create a folder called "mails" in resources/views/ directory.
- In the resources/views/mails/ directory create a index.blade.php, and copy the following code in that file:
<!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. Now we create the template for email content.
- In the "resources/views/mails/" folder create a "mail.blade.php" file with this content:
<h1>Hi, {{ $name }}</h1>
<p>Sending Mail from Laravel.</p>

@isset($img)
<img src="{{ $message->embed($img) }}">
@endisset
8. Add the following lines in routes/web.php:
Route::get('/sendmail','MailController@index');
Route::name('sendmail')->post('/sendmail','MailController@sendEmail');
9. Access the following address in your browser:
//localhost:8000/sendmail
- It will display the content created in "resources/views/mails/index.blade.php", a page like in this image:

Emails index page

10. Select the type of email you want to send, and click the "Send" button.
- After sending the email, it will display a message like this:
Email Sent. Check your inbox

Queueing Email

Sending email messages can lengthen the response time of your application, many developers choose to queue email messages for background sending.
To queue a mail message, use the queue() method instead of send():
Mail::to('to_mail@example.com')->queue(new MailableClass($data));

Delayed Message Queueing

You can use the later() method to delay the delivery of a queued email.
The later() method accepts a DateTime instance as its first argument, indicating when the message should be sent:
$when = Carbon\Carbon::now()->addMinutes(10);

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

Queueing by Default

If you have mailable classes that you want to always be queued, you may implement the ShouldQueue contract on the class.
Even if you call the send() method when mailing, the mailable will still be queued:
use Illuminate\Contracts\Queue\ShouldQueue;

class ClassName extends Mailable implements ShouldQueue {
  //
}

- Documentation: Laravel - Mail

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Sending Email, Mailables

Last accessed pages

  1. Common PHP Errors and Solutions (9771)
  2. PHP getElementById and getElementsByTagName (49471)
  3. Mysql SELECT JOIN tables on two different Databases (4498)
  4. jQuery UI draggable - Drag elements (11448)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142520)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (523)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (62)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)