#laravel mail configuration env
Explore tagged Tumblr posts
devscriptschool · 8 months ago
Text
How to deploying Laravel projects on a live server – Complete Step-by-Step Guide
Learn How to deploying Laravel projects on a live server with this comprehensive guide. Step-by-step instructions on setting up hosting, configuring files, and deploying your Laravel app smoothly.Read Laravel Docs
How to deploying Laravel projects on a live server, you’ll need to follow a structured process. Here’s a step-by-step guide to help you:
Tumblr media
1. Purchase Domain and Hosting
Make sure you have a domain and a hosting plan. Most shared hosting plans (like cPanel-based ones) or a VPS will work for Laravel, but ensure your server supports PHP and MySQL and meets Laravel’s requirements (PHP version, required extensions, etc.).
2. Prepare Your Laravel Project
Make sure your Laravel project is working locally.
Run the following command to clear any cached configuration and to optimize the project:
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
Set up your environment variables (.env file). Make sure they are correctly configured for the live server (e.g., database, mail, and app URL settings).
3. Zip and Upload Your Laravel Project
Compress your entire Laravel project folder (without the node_modules and vendor directories) into a .zip file.
Use FTP (with FileZilla or any other FTP client) or File Manager in cPanel to upload the .zip file to your server. Typically, upload the file to the public_html or a subdirectory within it if you want to run your Laravel app in a subdirectory.
4. Extract the Files
Once uploaded, use File Manager in your hosting control panel to extract the .zip file.
5. Set Up the Public Directory
By default, Laravel’s entry point is the public folder, which contains the index.php file. On a shared hosting server:
Move everything in the public folder (including the .htaccess and index.php files) to the root directory (usually public_html).
Edit the index.php file to update the paths:
Change:
require __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
To:
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
This ensures that Laravel can find the necessary files in the correct directory.
6. Set File Permissions
Ensure that the following directories are writable by the server:
/storage
/bootstrap/cache
Use the following command via SSH (if available) or through the hosting file manager:chmod -R 775 storage chmod -R 775 bootstrap/cache
7. Set Up a Database
Create a MySQL database and a user with privileges in cPanel (or via SSH if using VPS).
Update the .env file with your database credentials:
DB_HOST=localhost DB_DATABASE=your_database_name DB_USERNAME=your_database_username DB_PASSWORD=your_database_password
8. Install Composer Dependencies
If you have SSH access:
SSH into your server using a terminal or a tool like PuTTY.
Navigate to your project directory
cd /path/to/your/project
Run Composer to install the dependencies:
composer install --optimize-autoloader --no-dev
If you don’t have SSH access, you can run composer install locally, zip the vendor folder, and upload it to the server.
9. Run Migrations
If you have SSH access, run the following command to migrate the database:
php artisan migrate --force
If you don’t have SSH access, you can run the migrations locally and then export/import the database to the server via phpMyAdmin.
10. Set App Key
Generate a new application key if you haven’t already:php artisan key:generate
Ensure the key is set in the .env file:
Read Full Tutorials
0 notes
codehunger · 3 years ago
Text
peer certificate cn did not match expected laravel
peer certificate cn did not match expected laravel
Hello, buddy I hope you are doing well, in today’s article we will see how we can resolve the issue peer certificate did not match Stream Socket Enable Crypto Error in laravel. If you are reading this article it means you are trying to send an email from your live server but you are unable to do so due to this CN did not match error. Definitely, you go to the StackOverflow and some others sites…
View On WordPress
0 notes
websolutionstuff · 4 years ago
Text
0 notes
prevajconsultants · 8 years ago
Text
Small Business Management System (PHP Scripts)
Small Business Management System (SMBS) by AMDT, LLC
About Small Business Management System
Small Business Management System is a lightweight platform based on Laravel framework that suitable for both small businesses and freelancers to manage invoices, projects, track expenses, and contacts.
Requirements - SSH access - Composer - MySQL database - PHP>=5.6.4
Features - Invoicing system Create quick invoices Add items which can also be pre entered as inventory Log manual payments Allow your clients to pay via Stripe using their credit cards - Expenses tracker Easily view add your expenses and you can sort them by year. Track project tasks payments as expenses Associate an expense with a registered user - Project management Create a project and assign it to a client (user must have a client role to be available in projects) Create milestones Add tasks to milestones Assign individual tasks to team members Assign team members to the project Communicate easily with clients and team members within the project Share files within the project - Contacts Manage business contacts in a central location Contacts are available to users as business directory - User management - Roles and permissions Complete access control for each module in the application Create roles and assign permissions on who should should read, create, update or delete records
INSTALLATION This is a Laravel based application. Please review Laravel documentation to understand how to configure it. If you need assistance with installation, please contact us. - Extract contents to your desired root directory - Create a MySQL database - Copy .env.example file in the root of the application to .env - Edit .env file to match your disired configuration including database connection - Open terminal inside root directory and run composer install - Once composer completes installing vendors, run php artisan migrate --seed - Default user account is [email protected] / password
Support Technical support is not included in this application. Please contact Evanto Team for support. Bugs can be reported at http://ift.tt/2s52z9r and we will fix them with the next update. We are continually working to make this application better. Suggestions are also welcome.
- We offer installation and application support at a small fee. Please visit http://ift.tt/2rzPhy2 for more information.
Security Vulnerabilities
If you discover a security vulnerability within the application, please send an e-mail to Taylor [email protected]. All security vulnerabilities will be promptly addressed.
from CodeCanyon new items http://ift.tt/2swgnek via IFTTT https://goo.gl/zxKHwc
0 notes
php-sp · 5 years ago
Text
TMail - Multi Domain Temporary Email System
New Post has been published on https://intramate.com/php-scripts/tmail-multi-domain-temporary-email-system/
TMail - Multi Domain Temporary Email System
LIVE PREVIEWGet it now for only $30
8th February, 2020 – Download email option is now available in v5.5 with other automatically generation of API key in Admin Panel. This version also contains few bug fixes as well. Click here to see full changelog
TMail is simple to use, fast and mobile ready temporary email system with impressive feature set. It takes just 3 min to install TMail on your server. You can watch video tutorial on how to install TMail here – https://www.youtube.com/watch?v=QcIeTlGNJqo
Requirements
Below are server requirements. Usually, all major hosting providers covers each and every requirement specified below.
Server Requirements
PHP >= 7.1.3
MySQL >= 5.1
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
XML PHP Extension
Ctype PHP Extension
JSON PHP Extension
BCMath PHP Extension
IMAP PHP Extension
iconv PHP Extension
ZIP PHP Extension
Set allow_url_fopen = ON
Email with IMAP Support
Default Email Forwarder (Catch all Email)
Everything which requires Laravel to run
Note : New version of TMail will not work in sub directory. You can either install TMail on Sub Domain or a Proper Domain
Don’t hesitate to contact if you have any questions
Support
Need help in installing? Did you find any bug? Having some amazing ideas? Throw them here
Top quality support with 48hrs response time is always available to support you with any question or query you might have.
Feedback
Your honest review is always important. It encourages and helps to improve my product.
Special Thanks To
Omar Abubker – Arabic Translation – Connect RhoG725 – Spanish Translation – Connect
Changelog
v5.5 - 3 February 2020 - Added ability to Download Email - Added missing logout on mobile screens - Added functionality to automatically generate API Key in Admin Panel - Fixed console errors - Fixed ENV file getting cleared v5.4 - 2 December 2019 - Added more refined Ad Spaces - Fixed page url appended if set as homepage - Fixed API Issues - Fixed Password Reset Issue - Fixed Logo getting replaced after update issue v5.3 - 4 October 2019 - Re-organised Admin Panel - Added ability to add custom header for Pages (for Meta Tags, etc) - Added function to delete emails after specific seconds, hours, minutes and days - Fixed menu saving issue - Fixed weird code being shown with Google Adsense - Fixed console error in Admin Panel - Fixed "View All Emails" button being non functional on iPad / iPhone - Fixed inline images not being displayed - Fixed TMail buttons colors going back to default after language change v5.2 - 8 August 2019 - Added WordPress Blog Integration - Added support to delete emails via CRON - Added support to check for emails in CC field - Added ability to change timezone - Fixed attachments not getting deleted after email deletion - Fixed Visual Texts - Fixed Forbidden email Ids being case insensitive v5.11 - 13 June 2019 - Open Social Media Links in New Tab - Add Custom Header Field - Open Email Content Links in New Tab - Ads and Custom Code Issues v5.1 - 5 June 2019 - Added IP Logs - Added Custom CSS and JS Options - Fixed Social Links Issue - Fixed Ad Space Issues v5.0 - 2 June 2019 - Revamped UI and Backend Functionality - Upgraded App to Utilize Laravel Framework - Page Module - Menu Module - Multiple API Keys - Auto Generate Email - Stats Functionality - Social Media Links - Support for PHP v7.1 and above v4.3.7 - 5 March 2019 - Added Ads on Homepage (Top & Bottom) - Added Language support for Push Notifications - Fixed error on PHP 7.0 (Modern Layout) v4.3.6 - 19 January 2019 - Added ability to change application colors from Admin Panel (Modern Layout) - Added ability to logout from Admin Panel - Fixed UI issue related to switching email on mobile - Fixed Clear email button issue on mobile v4.3.5 - 12 January 2019 - Added "Test SMTP Connection" in Admin Panel - Fixed 'DIE' notification error - Fixed countdown issue in Modern - Minor Design Fix v4.3.4 - 30 December 2018 - Fixed PHP Server Variables Issues - Minor Design Fix v4.3.3 - 26 December 2018 - Added API Support - Added countdown in Modern Layout v4.3.2 - 16 December 2018 - Fixed loading screen issue - Fixed translation issues in few seconds - Fixed timezone bug v4.3.1 - 24 November 2018 - Fixed attachment issue while deleting or download email - Auto delete attachments after X days based on delete emails settings v4.3 - 22 November 2018 - Added attachments functionality - Added ability to encode email ID in URL - Fixed minor code issues v4.2 - 9 October 2018 - Fixed language string - Fixed bug in switch ID drop-down in Modern Layout - Fixed mails not getting cleared after email IDs are switched v4.1 - 16 August 2018 - Fixed German Language Issue - Push Notifications in Modern Layout - Ability to change Timezone - The ability for the user to Clear Email List - Tracking Codes can now be added directly from Admin Panel v4.0 - 15 August 2018 - Modern Layout Released - Menu Links Support - Minor Bug Fixes v3.4 - 3 July 2018 - Ability to enable or disable Push Notifications - Address not allocated Bug Fix - Minor Bug Fixes v3.3 - 7 April 2018 - Added ability to save a list of Emails - Added Web Notifications - Added ability to set Default language in Admin Panel - Minor Bug Fixes v3.2 - 26 February 2018 - Added Searchability for EMails - Added Multi - Email Functionality - Minor Bug Fixes v3.1 - 20 October 2017 - Added Admin Panel - Fixed Minor Cosmetic Issues - Optimized Configuration and Options Data v3.0 - 11 September 2017 - Added ability to save IP Logs with Date and EMail-ID created - Added option to use or not to use SSL for connecting to server - Added configurable about us - Added forbidden mail ids - Optimized Downloading of EMails - Fixed address attribute PHP Notice - Fixed countdown timer - Fixed total emails count in the title bar v2.2 - 19 August 2017 - Added ability to view total mails count in the title bar - Added 2 more languages (German & Polish) - Fixed minor bugs and cosmetic issues v2.1 - 28 July 2017 - Added 7 different languages support. - Fixed iPhone blank email. - Fixed blank email received from some email servers. v2.0 - 7 July 2017 - Added Custom Email ID Option - Added Ads Support - Added moving countdown for retrieval of new emails - Added option to customize 'After X number of days, emails gets deleted from server' - Added option to set refresh time for retrieval of new emails - Optimized JS for setting up Email ID - Optimized security - Fixed minor bug for Download Email option on some servers - Fixed formatting issue on Email v1.2 - 29 June 2017 - Added button for getting new Email ID - Fixed CSS issue - Fixed responsive issue on iPhone 4 and iPhone 4s v1.1 - 25 June 2017 - Fixed accordion expand issue - Fixed download button issue - Optimized retrieval of new emails v1.0 - 22 June 2017 - Initial Release! Yay!
LIVE PREVIEWGet it now for only $30
0 notes
openwebsolutions · 6 years ago
Text
How to set up mail functionalities with postmark package in your Laravel project
New Post has been published on http://blog.openwebsolutions.in/set-up-mail-functionalities-postmark-package-laravel-project/
How to set up mail functionalities with postmark package in your Laravel project
Postmark is globally used package which is used to set up inbound and outbound mail functionality from your server. Postmark provides lightning and fast delivery of the transactional emails.
To set up mail configuration with postmark is an easy way to manage your mail services and send transactional emails to the user’s mail account. It is durable fast and you can check the mail status from postmark dashboard.
After setting up the postmark account, you will have the access of the server credentials and you can set your server in the postmark dashboard. You can now set up the postmark service into your project folder.
You need to go to the base path of your Laravel project folder and run the following command and install the package.
$ composer require coconutcraig/laravel-postmark
This command will automatically register the package into your project folder.
Now you can publish the config file optionally by typing the following command:
php artisan vendor:publish --provider="Coconuts\Mail\PostmarkServiceProvider" --tag="config"
Now you can update the .env file of your project and update the following lines.
MAIL_DRIVER=postmark POSTMARK_SECRET=YOUR-SERVER-KEY-HERE
If required you may run the clear config cache from your project folder on the terminal and that will successfully setup the postmark mail functionality. Now you can send the mail by using SMTP, log, mailgun, etc.
0 notes
getpagespeed · 6 years ago
Text
Laravel Mail Configuration
If you have configured your server to correctly send outgoing emails, you don’t need any third party services.
Here’s Laravel 5 configuration to send email using local MTA (sendmail driver). Add the following to your .env file:
MAIL_DRIVER=sendmail MAIL_HOST=localhost MAIL_PORT=25 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null [email protected] MAIL_FROM_NAME="Site…
View On WordPress
0 notes
zz04-com · 7 years ago
Text
LaraClassified v5.4 – Geo 分类广告CMS破解版
系统简介
系统亮点
在线演示
功能介绍
系统需求
更新日志
安装方法
更新方法
目录
系统简介
LaraClassified是一个强大的广告分类CMS,具有开源和可调整的应用程序具有完全响应式设计。 基于Laravel和Bootstrap(HTML5&CSS3)构建,功能相对很完善。
在这里用户可以按照地区发布广告内容(也可以是二手、租赁等内容),访客可根据地理位置自动展示周边内容。
系统亮点
使用更多人喜欢的响应式设计
连接外部服务,如:贝宝,亚马逊SES,Mailgun,Mandrill,Sparkpost,Twilio,Nexmo,Facebook(OAuth),谷歌(Adsense,OAuth,地图)等等,为网站盈利助力。
易于使用,为您节省时间。 只需2分钟即可安装。
多语言,模板分离等。
在线演示
前台:http://laraclassified.bedigit.com
密码: 123456
后台:http://laraclassified.bedigit.com/admin
密码: 123456
功能介绍
Custom Fields (Create your own Classified Ads, Auto Deals, Real Estate, Directory Listings or Jobs Portal websites)
Clean and Modern Design
Fully Responsive (also in Admin panel)
Built with PHP/MySQL & HTML5/CSS3
Frameworks: Laravel, Bootstrap, jQuery, VueJS
Geo location supported (with Maxmind free or pro database)
Multi Countries (Switch to Multi Countries or Single Country)
Multi Currencies
Multilingual Support (English, French, Spanish and Arabic Included)
Support for RTL direction
Unlimited Colors
Homepage Customization (Change and Order the Home Sections from the Admin panel)
PayPal Integrated
Google Adsense integrated
Google Maps integrated
Twilio and Nexmo APIs integration
Facebook comment integrated
ReCaptcha integrated
Turn ON/OFF Ads activation Option
Turn ON/OFF User account activation Option
Allow guests to post an ad without being logged
Email Notifications (Using local SMTP or Amazon SES, Mailgun, Mandrill, or Sparkpost API)
SMS Notifications (Using Twilio or Nexmo API)
Resend Mail or SMS verification feature (Get more users with valid email or phone number)
CMS for Static pages (Create pages like: About Us, FAQ, Terms & Privacy, etc.)
Contact page (Contact form & Google maps)
Website Sitemap page
Google XML Sitemap
RSS feeds generator
List of countries page (If activated, SEO supported)
SEO optimized
Website backup (Admin panel module)
Blacklist (Admin panel module)
Plans/Packages (for Premium Ads)
Front End Listing Submission
Social Networks Login (Facebook, Google)
Protecting the users phone number against crawler
Well commented code.
Ready to use
Free Updates
and much more..
系统需求
PHP 7.1.3 或更新 (需要一些 PHP扩展,具体见安装第一步的扩展环境检查.)
OpenSSL PHP 扩展
PDO PHP 扩展
Mbstring PHP 扩展
Tokenizer PHP 扩展
XML PHP 扩展
GD 或 Imagick
PHP Fileinfo 扩展
PHP Zip Archive
Rewrite 模块 (Apache 或 Nginx)
更新日志
Version 5.4 Aug 9, 2018
Security vulnerability fixed (mentioned in the Laravel v5.6.30 Security Release).
Version 5.3 Jul 31, 2018
Bugs fixes.
Version 5.2 Jul 30, 2018
Admin panel: User Roles and Permissions (ACL) system added.
Minor improvements.
Bugs fixes.
Version 5.1 Jun 9, 2018
INFORMATION
By upgrading your website to the v5.1 you have to activate all the purchased plugins (add-ons) from the Admin panel → Plugins.
More backup features added (to prevent data losing).
Ability to disable the ads report pages indexation on the search engines added.
Ability to hide all the footer links added.
Cities columns option added in the homepage location area management.
Admin panel: Languages creation/edition forms improved.
Allow admin to force UTF-8 encoding for Dates (to prevent the Dashboard Charts display issue).
Create a new token if the post or user (email/phone number) is marked as unverified.
Minor improvements.
Bugs fixes.
Version 5.0 May 12, 2018
Admin panel: Bulk Items Deletion added.
HTTPS support fixed.
Minor improvements.
Version 4.9 May 4, 2018
INFORMATION
From the v4.9 the script requires PHP 7.1.3 or higher.
If your current version is v4.3 or lower, you have to read the v4.4 caution before starting the upgrade.
You have to clear your browser cache after the upgrade.
Support for Laravel 5.6.* (with several Laravel Security Fixes).
Russian, Thai, Portuguese, Turkish and Georgian languages files added.
Synchronization of missing lines of languages files during the website upgrade, or through the Admin.
More options for the homepage categories area management.
New Messages Auto-Checking (with configurable timer) feature added.
Enable/Disable the "Cities extended searches" from the Admin panel.
The Admin panel list pages is now responsive.
Cookie Consent Alert (to comply for EU law). Can be enabled from the Admin panel.
Display the County (or State) when selecting cities (in cities suggestion).
Click on the drag and drop zone to select pictures from your computer.
Optimization of Laravel Eloquent Queries with Eager Loading (to accept large databases).
The system no longer removes the 'included languages' files on languages deletion.
Replace the 'Packages' step by 'Payment' in ads posting process.
All categories (including 'job-*' categories types) now accept images uploading for ads.
Number Of Views/Items Counter: Shorten long numbers to K/M/B.
HTML Sitemap page improved.
The /public/uploads/ directory contents has been moved in the /storage/app/public/ directory.
XML Sitemaps fixed (Bug appeared by activating the multi-countries feature).
Links in the ads pictures slider (appeared on Firefox 59.*)
Bug fixes.
Minor improvements.
安装方法
因程序基于Laravel框架,程序需要指定二级目录作为运行目录,安装时候需要单独设置一下:
设置网站目录和程序运行目录
网站目录例如/home/reishi/topide.com
运行目录则设置成/home/reishi/topide.com/public/
如有不懂请咨询主机服务商或好友或度娘。
然后建立数据库,解压缩文件,将文件上传。
运行http://yoursite.com/install 按照提示检查系统环境,
检测通过输入数据库信息和产品授权码,在Purchase Code里输入
nulled-by-reishi 然后按照提示一步一步进行安装。
更新方法
注意:更新之前请备份数据库、语言包以及更改过的CSS文件。
解压缩文件, 除了/.env文件和/ public / uploads 目录之外的全部内容,上传覆盖。
然后访问你的网站或打开http://yoursite.com/upgrade网址进行更新。
如果更新过程中出现了401错误时,请到网站后台检查,此时更新应该就是完成了。
from 站长源码 https://zz04.net/2839.html
0 notes
technoknol · 7 years ago
Text
How to send test mail in Laravel via Terminal/Tinker
How to Send test mail in Laravel via Terminal/Tinker
Just a small piece of code to test your mail settings and fire a test mail right from your terminal. I needed this when changing configuration in .env file to check different settings. But everytime changing setting and then running your piece of code which sends mail is kind of boring and lengthy. Instead just change config, fire a command is quick to test your settings. So I did it via Tinker…
View On WordPress
0 notes
mbaljeetsingh · 7 years ago
Text
Understanding and Working with Files in Laravel
File uploads is one the most commonly used features on the web. From uploading avatars to family pictures to sending documents via email, we can't do without files on the web.
In today’s article will cover all the ways to handle files in Laravel. If you are new to Laravel, browse the courses or navigate to the tutorials section. After reading the article, If we left something out please let us know in the comments and we’ll update the post accordingly.
Handling of files is another thing Laravel has simplified in its ecosystem. Before we get started, we’ll need a few things. First, a Laravel project. There are a few ways to create a new Laravel project, but let's stick to composer for now.
composer create-project --prefer-dist laravel/laravel files
Where files is the name of our project. After installing the app, we’ll need a few packages installed, so, let’s get them out of the way. You should note that these packages are only necessary if you intend to save images to Amazon’s s3 or manipulate images like cropping, filters etc.
composer require league/flysystem-aws-s3-v3:~1.0 intervention/image:~2.4
After installing the dependencies, the final one is Mailtrap. Mailtrap is a fake SMTP server for development teams to test, view and share emails sent from the development and staging environments without spamming real customers. So head over to Mailtrap and create a new inbox for testing.
Then, in welcome.blade.php update the head tag to:
<meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>File uploads</title> <style> * { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; } </style>
Modify the body contents to:
<form action="/process" enctype="multipart/form-data" method="POST"> <p> <label for="photo"> <input type="file" name="photo" id="photo"> </label> </p> <button>Upload</button> </form>
For the file upload form, the enctype="multipart/form-data" and method="POST" are extremely important as the browser will know how to properly format the request. is Laravel specific and will generate a hidden input field with a token that Laravel can use to verify the form submission is legit.
If the CSRF token does not exist on the page, Laravel will show “The page has expired due to inactivity” page.
Now that we have our dependencies out of the way, let's get started.
Understanding How Laravel Handles Files
Development as we know it in 2018 is growing fast, and in most cases there are many solutions to one problem. Take file hosting for example, now we have so many options to store files, the sheer number of solutions ranging from self hosted to FTP to cloud storage to GFS and many others.
Since Laravel is framework that encourages flexibility, it has a native way to handle the many file structures. Be it local, Amazon's s3, Google's Cloud, Laravel has you covered.
Laravel's solution to this problem is to call them disks. Makes sense, any file storage system you can think of can be labeled as a disk in Laravel. To this regard, Laravel comes with native support for some providers (disks). We have: local, public, s3, rackspace, FTP etc. All this is possible because of Flysystem.
If you open config/filesystems.php you’ll see the available disks and their respected configuration.
File Uploads in Laravel
From the introduction section above, we have a form with a file input ready to be processed. We can see that the form is pointed to /process. In routes/web.php, we define a new POST /process route.
use Illuminate\Http\Request; Route::post('process', function (Request $request) { $path = $request->file('photo')->store('photos'); dd($path); });
What the above code does is grab the photo field from the request and save it to the photos folder. dd() is a Laravel function that kills the running script and dumps the argument to the page. For me, the file was saved to "photos/3hcX8yrOs2NYhpadt4Eacq4TFtpVYUCw6VTRJhfn.png". To find this file on the file system, navigate to storage/app and you’ll find the uploaded file.
If you don't like the default naming pattern provided by Laravel, you can provide yours using the storeAs method.
Route::post('process', function (Request $request) { // cache the file $file = $request->file('photo'); // generate a new filename. getClientOriginalExtension() for the file extension $filename = 'profile-photo-' . time() . '.' . $file->getClientOriginalExtension(); // save to storage/app/photos as the new $filename $path = $file->storeAs('photos', $filename); dd($path); });
After running the above code, I got "photos/profile-photo-1517311378.png".
Difference Between Local and Public Disks
In config/filesystems.php you can see the disks local and public defined. By default, Laravel uses the local disk configuration. The major difference between local and public disk is that local is private and cannot be accessed from the browser while public can be accessed from the browser.
Since the public disk is in storage/app/public and Laravel's server root is in public you need to link storage/app/public to Laravel's public folder. We can do that with our trusty artisan by running php artisan storage:link.
Uploading Multiple Files
Since Laravel doesn't provide a function to upload multiple files, we need to do that ourselves. It’s not much different from what we’ve been doing so far, we just need a loop.
First, let’s update our file upload input to accept multiple files.
<input type="file" name="photos[]" id="photo" multiple>
When we try to process this $request->file('photos'), it's now an array of UploadedFile instances so we need to loop through the array and save each file.
Route::post('process', function (Request $request) { $photos = $request->file('photos'); $paths = []; foreach ($photos as $photo) { $extension = $photo->getClientOriginalExtension(); $filename = 'profile-photo-' . time() . '.' . $extension; $paths[] = $photo->storeAs('photos', $filename); } dd($paths); });
After running this, I got the following array, since I uploaded a GIF and a PNG:
array:2 [▼ 0 => "photos/profile-photo-1517315875.gif" 1 => "photos/profile-photo-1517315875.png" ]
Validating File Uploads
Validation for file uploads is extremely important. Apart from preventing users from uploading the wrong file types, it’s also for security. Let me give an example regarding security. There's a PHP configuration option cgi.fix_pathinfo=1. What this does is when it encounters a file like https://site.com/images/evil.jpg/nonexistent.php, PHP will assume nonexistent.php is a PHP file and it will try to run it. When it discovers that nonexistent.php doesn't exists, PHP will be like "I need to fix this ASAP" and try to execute evil.jpg (a PHP file disguised as a JPEG). Because evil.jpg wasn’t validated when it was uploaded, a hacker now has a script they can freely run live on your server… Not… good.
To validate files in Laravel, there are so many ways, but let’s stick to controller validation.
Route::post('process', function (Request $request) { // validate the uploaded file $validation = $request->validate([ 'photo' => 'required|file|image|mimes:jpeg,png,gif,webp|max:2048' // for multiple file uploads // 'photo.*' => 'required|file|image|mimes:jpeg,png,gif,webp|max:2048' ]); $file = $validation['photo']; // get the validated file $extension = $file->getClientOriginalExtension(); $filename = 'profile-photo-' . time() . '.' . $extension; $path = $file->storeAs('photos', $filename); dd($path); });
For the above snippet, we told Laravel to make sure the field with a name of photo is required, a successfully uploaded file, it’s an image, it has one of the defined mime types, and it’s a max of 2048 kilobytes ~~ 2 megabytes.
Now, when a malicious user uploads a disguised file, the file will fail validation and if for some weird reason you leave cgi.fix_pathinfo on, this is not a means by which you can get PWNED!!!
If you head over to Laravel's validation page you’ll see a whole bunch of validation rules.
Moving Files to the Cloud
Okay, your site is now an adult, it has many visitors and you decide it’s time to move to the cloud. Or maybe from the beginning, you decided your files will live on separate server. The good news is Laravel comes with support for many cloud providers, but, for this tutorial, let's stick with Amazon.
Earlier we installed league/flysystem-aws-s3-v3 through composer. Laravel will automatically look for it if you choose to use Amazon S3 or throw an exception.
To upload files to the cloud, just use:
$request->file('photo')->store('photos', 's3');
For multiple file uploads:
foreach ($photos as $photo) { $extension = $photo->getClientOriginalExtension(); $filename = 'profile-photo-' . time() . '.' . $extension; $paths[] = $photo->storeAs('photos', $filename, 's3'); }
Users may have already uploaded files before you decide to switch to a cloud provider, you can check the upcoming sections for what to do when files already exist.
Note: you’ll have to configure your Amazon s3 credentials in config/filesystems.php**.**
Sending Files as Email Attachments
Before we do this, let's quickly configure our mail environment. In .env file you will see this section
MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null
We need a username and password which we can get at Mailtrap.io. Mailtrap is really good for testing emails during development as you don’t have to crowd your email with spam. You can also share inboxes with team members or create separate inboxes.
First, create an account and login:
Create a new inbox
Click to open inbox
Copy username and password under SMTP section
youtube
After copying credentials, we can modify .env to:
MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=8a1d546090493b MAIL_PASSWORD=328dd2af5aefc3 MAIL_ENCRYPTION=null
Don't bother using mine, I deleted it.
Create your mailable
php artisan make:mail FileDownloaded
Then, edit its build method and change it to:
public function build() { return $this->from('[email protected]') ->view('emails.files_downloaded') ->attach(storage_path('app/file.txt'), [ 'as' => 'secret.txt' ]); }
As you can see from the method above, we pass the absolute file path to the attach() method and pass an optional array where we can change the name of the attachment or even add custom headers. Next we need to create our email view.
Create a new view file in resources/views/emails/files_downloaded.blade.php and place the content below.
<h1>Only you can stop forest fires</h1> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Labore at reiciendis consequatur, ea culpa molestiae ad minima est quibusdam ducimus laboriosam dolorem, quasi sequi! Atque dolore ullam nisi accusantium. Tenetur!</p>
Now, in routes/web.php we can create a new route and trigger a mail when we visit it.
use App\Mail\FileDownloaded;
Route::get('mail', function () { $email = '[email protected]'; Mail::to($email)->send(new FileDownloaded); dd('done'); });
If you head over to Mailtrap, you should see this.
Storage Facade for When Files Already Exist
In an application, it’s not every time we process files through uploads. Sometimes, we decide to defer cloud file uploads till a certain user action is complete. Other times we have some files on disk before switching to a cloud provider. For times like this, Laravel provides a convenient Storage facade. For those who don’t know, facades in Laravel are class aliases. So instead of doing something like Symfony\File\Whatever\Long\Namespace\UploadedFile, we can do Storage instead.
Choosing a disk to upload file. If no disk is specified, Laravel looks in config/filesystems.php and use the default disk.
Storage::disk('local')->exists('file.txt');
use default cloud provider
// Storage::disk('cloud')->exists('file.txt'); will not work so do: Storage::cloud()->exists('file.txt');
Create a new file with contents
Storage::put('file.txt', 'Contents');
Prepend to file
Storage::prepend('file.txt', 'Prepended Text');
Append to file
Storage::append('file.txt', 'Prepended Text');
Get file contents
Storage::get('file.txt')
Check if file exists
Storage::exists('file.txt')
Force file download
Storage::download('file.txt', $name, $headers); // $name and $headers are optional
Generate publicly accessible URL
Storage::url('file.txt');
Generate a temporary public URL (i.e files that won’t exists after a set time). This will only work for cloud providers as Laravel doesn’t yet know how to handle generation of temporary URLs for local disk.
Storage::temporaryUrl('file.txt’, now()->addMinutes(10));
Get file size
Storage::size('file.txt');
Last modified date
Storage::lastModified('file.txt')
Copy files
Storage::copy('file.txt', 'shared/file.txt');
Move files
Storage::move('file.txt', 'secret/file.txt');
Delete files
Storage::delete('file.txt');
// to delete multiple files Storage::delete(['file1.txt', 'file2.txt']);
Manipulating files
Resizing images, adding filters etc. This is where Laravel needs external help. Adding this feature natively to Laravel will only bloat the application since not installs need it. We need a package called intervention/image. We already installed this package, but for reference.
composer require intervention/image
Since Laravel can automatically detect packages, we don't need to register anything. If you are using a version of Laravel lesser than 5.5 read this.
To resize an image
$image = Image::make(storage_path('app/public/profile.jpg'))->resize(300, 200);
Even Laravel's packages are fluent.
You can head over to their website and see all the fancy effects and filters you can add to your image.
Don’t forget directories
Laravel also provides handy helpers to work with directories. They are all based on PHP iterators so they'll provide the utmost performance.
To get all files:
Storage::files
To get all files in a directory including files in sub-folders
Storage::allFiles($directory_name);
To get all directories within a directory
Storage::directories($directory_name);
To get all directories within a directory including files in sub-directories
Storage::allDirectories($directory_name);
Make a directory
Storage::makeDirectory($directory_name);
Delete a directory
Storage::deleteDirectory($directory_name);
Conclusion
If we left anything out, please let us know down in the comments. Also, checkout Mailtrap, they are really good and they will help you sail through the development phase with regards to debugging emails.
via Scotch.io http://ift.tt/2sHlNEp
0 notes
t-baba · 7 years ago
Photo
Tumblr media
How to Send Emails in Laravel
In this article, we're going to explore the Mail API in the Laravel web framework. Laravel takes advantage of the popular SwiftMailer library, which is easy to use and comes with a variety of email drivers to choose from. In the latter stages of the article, we'll go through an in-depth demonstration of the concepts discussed in the first half of the article.
Setting Up the Prerequisites
Laravel implements a wrapper on top of the SwiftMailer library that makes email management very easy to configure and use at the same time. You can find the default mail settings at config/mail.php.
<?php return [ /* |-------------------------------------------------------------------------- | Mail Driver |-------------------------------------------------------------------------- | | Laravel supports both SMTP and PHP's "mail" function as drivers for the | sending of e-mail. You may specify which one you're using throughout | your application here. By default, Laravel is setup for SMTP mail. | | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses", | "sparkpost", "log", "array" | */ 'driver' => env('MAIL_DRIVER', 'sendmail'), /* |-------------------------------------------------------------------------- | SMTP Host Address |-------------------------------------------------------------------------- | | Here you may provide the host address of the SMTP server used by your | applications. A default option is provided that is compatible with | the Mailgun mail service which will provide reliable deliveries. | */ 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), /* |-------------------------------------------------------------------------- | SMTP Host Port |-------------------------------------------------------------------------- | | This is the SMTP port used by your application to deliver e-mails to | users of the application. Like the host we have set this value to | stay compatible with the Mailgun e-mail application by default. | */ 'port' => env('MAIL_PORT', 587), /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */ 'from' => [ 'address' => env('MAIL_FROM_ADDRESS', '[email protected]'), 'name' => env('MAIL_FROM_NAME', 'Example'), ], /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol |-------------------------------------------------------------------------- | | Here you may specify the encryption protocol that should be used when | the application send e-mail messages. A sensible default using the | transport layer security protocol should provide great security. | */ 'encryption' => env('MAIL_ENCRYPTION', 'tls'), /* |-------------------------------------------------------------------------- | SMTP Server Username |-------------------------------------------------------------------------- | | If your SMTP server requires a username for authentication, you should | set it here. This will get used to authenticate with your server on | connection. You may also set the "password" value below this one. | */ 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), /* |-------------------------------------------------------------------------- | Sendmail System Path |-------------------------------------------------------------------------- | | When using the "sendmail" driver to send e-mails, we will need to know | the path to where Sendmail lives on this server. A default path has | been provided here, which will work well on most of your systems. | */ 'sendmail' => '/usr/sbin/sendmail -bs', /* |-------------------------------------------------------------------------- | Markdown Mail Settings |-------------------------------------------------------------------------- | | If you are using Markdown based email rendering, you may configure your | theme and component paths here, allowing you to customize the design | of the emails. Or, you may simply stick with the Laravel defaults! | */ 'markdown' => [ 'theme' => 'default', 'paths' => [ resource_path('views/vendor/mail'), ], ], ];
When it comes to sending mails, Laravel supports different drivers to choose from. As you can see, the default MAIL_DRIVER is set to smtp.
If you are going to use the smtp driver to send mails then you're also required to set other related settings like MAIL_HOST, MAIL_PORT, MAIL_ENCRYPTION, MAIL_USERNAME, and MAIL_PASSWORD.
On the other hand, if you are going to use the sendmail driver, then you want to make sure that the sendmail system path is set to the correct value in the config/mail.php file.
You can also set the from address that will be used while sending mails under the from key. And finally, if you want to use Markdown-based email rendering, you can set those settings under the markdown key.
The cherry on the top is that you could also use third-party email service providers like Mailgun, Mandrill, SES, and SparkPost. If you are using one of those services, you need to make sure that you set the corresponding settings in the config/services.php file.
So that was a basic introduction to the mail API related settings in Laravel. From the next section onwards, we'll go through a custom example that shows you how to send emails.
Create the Mailable Class
In this section, we'll create the mailable class, which will be used to send emails. The mailable class is responsible for sending emails using a mailer that's configured in the config/mail.php file. In fact, Laravel already provides an artisan command that allows us to create a base template.
php artisan make:mail DemoEmail
That should create a blank email template at app/Mail/DemoEmail.php, as shown in the following snippet.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { return $this->view('view.name'); } }
Let's replace the contents of that file with the following.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * The demo object instance. * * @var Demo */ public $demo; /** * Create a new message instance. * * @return void */ public function __construct($demo) { $this->demo = $demo; } /** * Build the message. * * @return $this */ public function build() { return $this->from('[email protected]') ->view('mails.demo') ->text('mails.demo_plain') ->with( [ 'testVarOne' => '1', 'testVarTwo' => '2', ]) ->attach(public_path('/images').'/demo.jpg', [ 'as' => 'demo.jpg', 'mime' => 'image/jpeg', ]); } }
There are two important methods the mailable class generally implements—__construct and build. The __construct method is used to initialize objects that you're supposed to use in the email template. On the other hand, the build method is used to initialize more email-specific values like from, view template, attachments and similar.
In our case, we've passed the $demo object as a constructor argument, and it's assigned to the demo public property.
In the build method, we've initialized an email-specific configuration.
The from is used to set an email address that'll be used as a from address.
Using the view method, you can set the email template that will be used while sending an email using this mailable. In our case, we've set it to mails.demo, and it means that you need to create a view template file at resources/views/mails/demo.blade.php.
Next, the text method is used to set up the plain text version of an email template.
As we've just discussed, the __construct method is used to set up objects that'll be used in the email template, you can also use the with method that allows you to set the view data of a message.
Next, we've used the attach method to attach an image with a message.
Of course, we need to create email templates that we're supposed to use while sending emails. Go ahead and create a file resources/views/mails/demo.blade.php as shown in the following snippet.
Hello <i></i>, <p>This is a demo email for testing purposes! Also, it's the HTML version.</p> <p><u>Demo object values:</u></p> <div> <p><b>Demo One:</b> </p> <p><b>Demo Two:</b> </p> </div> <p><u>Values passed by With method:</u></p> <div> <p><b>testVarOne:</b> </p> <p><b>testVarTwo:</b> </p> </div> Thank You, <br/> <i></i>
Also, let's create the plain text version of that file at resources/views/mails/demo_plain.blade.php.
Hello , This is a demo email for testing purposes! Also, it's the HTML version. Demo object values: Demo One: Demo Two: Values passed by With method: testVarOne: testVarOne: Thank You,
So that was the mailable class at your disposal, and we've not done yet as we need to use the Mail facade to actually send mails. In the very next section, we'll explore how you can use the Mail Facade to send emails using the DemoEmail Mailable class that was just created in this section.
Wrapping Up
In this section, we'll create an example to demonstrate how you can use the Mailable class that was created in the last section.
Let's create a controller file at app/Http/Controllers/MailController.php with the following contents.
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Mail\DemoEmail; use Illuminate\Support\Facades\Mail; class MailController extends Controller { public function send() { $objDemo = new \stdClass(); $objDemo->demo_one = 'Demo One Value'; $objDemo->demo_two = 'Demo Two Value'; $objDemo->sender = 'SenderUserName'; $objDemo->receiver = 'ReceiverUserName'; Mail::to("[email protected]")->send(new DemoEmail($objDemo)); } }
It's important to note that we've included the Illuminate\Support\Facades\Mail Facade that will be used to send an email. In the send method, the following statement is responsible for sending an email by initialising the App\Mail\DemoEmail Mailable in the first place.
Mail::to("[email protected]")->send(new DemoEmail($objDemo));
The to method of the Illuminate\Support\Facades\Mail Facade returns an instance of the \Illuminate\Mail\PendingMail class, which already contains an appropriate mailer configured in the config/mail.php file.
And finally, we use the send method of the \Illuminate\Mail\PendingMail class that sends an actual email.
To test it, let's add an associated route in the routes/web.php file.
// Email related routes Route::get('mail/send', 'MailController@send');
And with that in place, you can run the http://ift.tt/2BSrKyg URL to see if it works as expected.
On the other hand, if you want to test your email templates quickly, without sending actual emails, there's a provision in Laravel that allows you to log all outgoing emails.
To achieve that, you need to set the value of MAIL_DRIVER to log in the config/mail.php file. Next, you could run the aforementioned URL and inspect the log file to check if the email template was logged there.
If everything goes fine, you should see an email being logged to the storage/logs/laravel.log file.
That's pretty much it as far as the mail feature is concerned in Laravel, and that concludes this article as well.
Conclusion
Today, we went through the mail API that comes built into Laravel, and it also supports a variety of drivers as well.
Starting with basic concepts, we implemented the mailable class that is an essential element in the mail API in Laravel as we moved on. At the end, we also tested the mailable class by creating a custom controller to see if it actually works.
If you're just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.
I would love to know your feedback in the form of queries and comments using the feed below!
by Sajal Soni via Envato Tuts+ Code http://ift.tt/2lqIYf4
0 notes
codehunger · 4 years ago
Text
Send Mail In Laravel Using SMTP |Laravel - 8
Send Mail In Laravel Using SMTP |Laravel – 8
In this blog we will learn about how we can send mail in Laravel using SMTP, how we can configure SMTP in Laravel, I will use mailtrap SMTP to configure the Laravel application, I will put all the SMTP details in the .env file Laravel 8 provides a mail class to send an email. you can use several drivers for sending email in Laravel 8. you can use mailtrap, SMTP, Mailgun, Postmark, Amazon SES,…
Tumblr media
View On WordPress
0 notes
laravelvuejs · 8 years ago
Photo
Tumblr media
How to setup email configuration and send email in Laravel 5 Learn how to configure email in Laravel and send an email to the desired recipient. You will learn how to define mail settings in Laravel .env file which you can then use to define settings in your mail.php configuration file using the env() Laravel method. source
0 notes
mbaljeetsingh · 7 years ago
Text
How to Send Emails in Laravel
In this article, we're going to explore the Mail API in the Laravel web framework. Laravel takes advantage of the popular SwiftMailer library, which is easy to use and comes with a variety of email drivers to choose from. In the latter stages of the article, we'll go through an in-depth demonstration of the concepts discussed in the first half of the article.
Setting Up the Prerequisites
Laravel implements a wrapper on top of the SwiftMailer library that makes email management very easy to configure and use at the same time. You can find the default mail settings at config/mail.php.
<?php return [ /* |-------------------------------------------------------------------------- | Mail Driver |-------------------------------------------------------------------------- | | Laravel supports both SMTP and PHP's "mail" function as drivers for the | sending of e-mail. You may specify which one you're using throughout | your application here. By default, Laravel is setup for SMTP mail. | | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses", | "sparkpost", "log", "array" | */ 'driver' => env('MAIL_DRIVER', 'sendmail'), /* |-------------------------------------------------------------------------- | SMTP Host Address |-------------------------------------------------------------------------- | | Here you may provide the host address of the SMTP server used by your | applications. A default option is provided that is compatible with | the Mailgun mail service which will provide reliable deliveries. | */ 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), /* |-------------------------------------------------------------------------- | SMTP Host Port |-------------------------------------------------------------------------- | | This is the SMTP port used by your application to deliver e-mails to | users of the application. Like the host we have set this value to | stay compatible with the Mailgun e-mail application by default. | */ 'port' => env('MAIL_PORT', 587), /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */ 'from' => [ 'address' => env('MAIL_FROM_ADDRESS', '[email protected]'), 'name' => env('MAIL_FROM_NAME', 'Example'), ], /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol |-------------------------------------------------------------------------- | | Here you may specify the encryption protocol that should be used when | the application send e-mail messages. A sensible default using the | transport layer security protocol should provide great security. | */ 'encryption' => env('MAIL_ENCRYPTION', 'tls'), /* |-------------------------------------------------------------------------- | SMTP Server Username |-------------------------------------------------------------------------- | | If your SMTP server requires a username for authentication, you should | set it here. This will get used to authenticate with your server on | connection. You may also set the "password" value below this one. | */ 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), /* |-------------------------------------------------------------------------- | Sendmail System Path |-------------------------------------------------------------------------- | | When using the "sendmail" driver to send e-mails, we will need to know | the path to where Sendmail lives on this server. A default path has | been provided here, which will work well on most of your systems. | */ 'sendmail' => '/usr/sbin/sendmail -bs', /* |-------------------------------------------------------------------------- | Markdown Mail Settings |-------------------------------------------------------------------------- | | If you are using Markdown based email rendering, you may configure your | theme and component paths here, allowing you to customize the design | of the emails. Or, you may simply stick with the Laravel defaults! | */ 'markdown' => [ 'theme' => 'default', 'paths' => [ resource_path('views/vendor/mail'), ], ], ];
When it comes to sending mails, Laravel supports different drivers to choose from. As you can see, the default MAIL_DRIVER is set to smtp.
If you are going to use the smtp driver to send mails then you're also required to set other related settings like MAIL_HOST, MAIL_PORT, MAIL_ENCRYPTION, MAIL_USERNAME, and MAIL_PASSWORD.
On the other hand, if you are going to use the sendmail driver, then you want to make sure that the sendmail system path is set to the correct value in the config/mail.php file.
You can also set the from address that will be used while sending mails under the from key. And finally, if you want to use Markdown-based email rendering, you can set those settings under the markdown key.
The cherry on the top is that you could also use third-party email service providers like Mailgun, Mandrill, SES, and SparkPost. If you are using one of those services, you need to make sure that you set the corresponding settings in the config/services.php file.
So that was a basic introduction to the mail API related settings in Laravel. From the next section onwards, we'll go through a custom example that shows you how to send emails.
Create the Mailable Class
In this section, we'll create the mailable class, which will be used to send emails. The mailable class is responsible for sending emails using a mailer that's configured in the config/mail.php file. In fact, Laravel already provides an artisan command that allows us to create a base template.
php artisan make:mail DemoEmail
That should create a blank email template at app/Mail/DemoEmail.php, as shown in the following snippet.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { return $this->view('view.name'); } }
Let's replace the contents of that file with the following.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * The demo object instance. * * @var Demo */ public $demo; /** * Create a new message instance. * * @return void */ public function __construct($demo) { $this->demo = $demo; } /** * Build the message. * * @return $this */ public function build() { return $this->from('[email protected]') ->view('mails.demo') ->text('mails.demo_plain') ->with( [ 'testVarOne' => '1', 'testVarTwo' => '2', ]) ->attach(public_path('/images').'/demo.jpg', [ 'as' => 'demo.jpg', 'mime' => 'image/jpeg', ]); } }
There are two important methods the mailable class generally implements—__construct and build. The __construct method is used to initialize objects that you're supposed to use in the email template. On the other hand, the build method is used to initialize more email-specific values like from, view template, attachments and similar.
In our case, we've passed the $demo object as a constructor argument, and it's assigned to the demo public property.
In the build method, we've initialized an email-specific configuration.
The from is used to set an email address that'll be used as a from address.
Using the view method, you can set the email template that will be used while sending an email using this mailable. In our case, we've set it to mails.demo, and it means that you need to create a view template file at resources/views/mails/demo.blade.php.
Next, the text method is used to set up the plain text version of an email template.
As we've just discussed, the __construct method is used to set up objects that'll be used in the email template, you can also use the with method that allows you to set the view data of a message.
Next, we've used the attach method to attach an image with a message.
Of course, we need to create email templates that we're supposed to use while sending emails. Go ahead and create a file resources/views/mails/demo.blade.php as shown in the following snippet.
Hello <i></i>, <p>This is a demo email for testing purposes! Also, it's the HTML version.</p> <p><u>Demo object values:</u></p> <div> <p><b>Demo One:</b> </p> <p><b>Demo Two:</b> </p> </div> <p><u>Values passed by With method:</u></p> <div> <p><b>testVarOne:</b> </p> <p><b>testVarTwo:</b> </p> </div> Thank You, <br/> <i></i>
Also, let's create the plain text version of that file at resources/views/mails/demo_plain.blade.php.
Hello , This is a demo email for testing purposes! Also, it's the HTML version. Demo object values: Demo One: Demo Two: Values passed by With method: testVarOne: testVarOne: Thank You,
So that was the mailable class at your disposal, and we've not done yet as we need to use the Mail facade to actually send mails. In the very next section, we'll explore how you can use the Mail Facade to send emails using the DemoEmail Mailable class that was just created in this section.
Wrapping Up
In this section, we'll create an example to demonstrate how you can use the Mailable class that was created in the last section.
Let's create a controller file at app/Http/Controllers/MailController.php with the following contents.
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Mail\DemoEmail; use Illuminate\Support\Facades\Mail; class MailController extends Controller { public function send() { $objDemo = new \stdClass(); $objDemo->demo_one = 'Demo One Value'; $objDemo->demo_two = 'Demo Two Value'; $objDemo->sender = 'SenderUserName'; $objDemo->receiver = 'ReceiverUserName'; Mail::to("[email protected]")->send(new DemoEmail($objDemo)); } }
It's important to note that we've included the Illuminate\Support\Facades\Mail Facade that will be used to send an email. In the send method, the following statement is responsible for sending an email by initialising the App\Mail\DemoEmail Mailable in the first place.
Mail::to("[email protected]")->send(new DemoEmail($objDemo));
The to method of the Illuminate\Support\Facades\Mail Facade returns an instance of the \Illuminate\Mail\PendingMail class, which already contains an appropriate mailer configured in the config/mail.php file.
And finally, we use the send method of the \Illuminate\Mail\PendingMail class that sends an actual email.
To test it, let's add an associated route in the routes/web.php file.
// Email related routes Route::get('mail/send', 'MailController@send');
And with that in place, you can run the http://ift.tt/2BSrKyg URL to see if it works as expected.
On the other hand, if you want to test your email templates quickly, without sending actual emails, there's a provision in Laravel that allows you to log all outgoing emails.
To achieve that, you need to set the value of MAIL_DRIVER to log in the config/mail.php file. Next, you could run the aforementioned URL and inspect the log file to check if the email template was logged there.
If everything goes fine, you should see an email being logged to the storage/logs/laravel.log file.
That's pretty much it as far as the mail feature is concerned in Laravel, and that concludes this article as well.
Conclusion
Today, we went through the mail API that comes built into Laravel, and it also supports a variety of drivers as well.
Starting with basic concepts, we implemented the mailable class that is an essential element in the mail API in Laravel as we moved on. At the end, we also tested the mailable class by creating a custom controller to see if it actually works.
If you're just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.
I would love to know your feedback in the form of queries and comments using the feed below!
via Envato Tuts+ Code http://ift.tt/2lq3bll
0 notes