Core points
- Laravel's command line tool Artisan can be extended to receive raw mail and use it in your application. This involves creating a new command, such as
php artisan email:parse
, which can be registered and executed in Artisan to retrieve the original message from the IO stream. - Use
php-mime-mail-parser
etc. to resolve the original message into a separate section. This allows retrieval of headers such as the subject and body of the email. The parsed mail can then be easily stored in the database. - This setting can also handle any attachments in the message. After retrieving attachments, you can create a file system object to save the file on the server. Additionally, depending on the tool or mail server used, different methods can be used to deliver mail to the application.
Introduction
You will see this often in project management or support management tools: You can reply to emails and it will automatically appear in your web application. These tools are able to import these emails directly into their systems.
In this article, we will learn how to deliver emails to our Laravel 4 application. To do this, we started with a brand new Laravel 4 project that was installed via Composer as shown below.
composer create-project laravel/laravel your-project-name --prefer-dist
Create Artisan command
In order to be able to import emails into our application, we must deliver the emails to our application via the command line. Fortunately, Laravel has a command line tool called Artisan that is capable of performing multiple tasks. To view a list of all tasks that Artisan can run, you can run php artisan list
in the root directory of your project.
In this case, we want it to perform a very specific task: accept the original email and use it in our application. Unfortunately, this is not one of the basic features Artisan can handle. We can easily extend it with the new command: php artisan email:parse
. We will then start Artisan and perform a specific task, called email:parse
in this case.
Our first step is to create this command. You can create a new command through Artisan's own command to create a new command. Simply run the following command in the root directory of the project:
php artisan command:make EmailParserCommand
If everything goes well, you will now find a file named app/commands
in the EmailParserCommand.php
directory. Open it in your favorite editor and view the $name
and $description
properties. We can customize it as needed. By giving it a clear name and description, the command will be listed well in the Artisan command list.
For example, I changed it to this:
/** * 控制臺命令名稱。 * * @var string */ protected $name = 'email:parse'; /** * 控制臺命令描述。 * * @var string */ protected $description = '解析傳入的電子郵件。';
Registering order
When we run php artisan email:parse
in the root of our project, you will receive a message stating that this command has not been registered yet. Our next step is to make sure this command is registered in Artisan. Let's open the app/start/artisan.php
file and add Artisan::add(new EmailParserCommand);
to the end of the file to register our newly created command. We can now run the list
command again to view the email:parse
command we listed. Please note that the name and description you just filled in will be displayed here.
Retrieve original email
Whenever a command is called through Artisan, it always calls the fire
method. So initially we have to add our email parsing here. The email is currently in our IO stream and we can retrieve it from php://stdin
. We open this IO stream and collect a small amount of emails until we read the entire stream.
composer create-project laravel/laravel your-project-name --prefer-dist
The email sent to our Artisan command is now located in the $rawEmail
variable. It is the entire email, containing the header, body and any attachments.
Schedule email
We now have the original email, but I prefer to split the email into multiple parts. I want to retrieve headers like topics and email body. We can write our own code to split all of these parts, but someone has created a package that we can use in our application. This package is able to divide our entire email into logical parts. Add the following line to your composer.json
file and run composer update
php artisan command:make EmailParserCommand
Now we need to make sure we can actually use this package in our commands, so we open our app/command/EmailParserCommand.php
again and add the following lines to the top:
/** * 控制臺命令名稱。 * * @var string */ protected $name = 'email:parse'; /** * 控制臺命令描述。 * * @var string */ protected $description = '解析傳入的電子郵件。';
Now we can parse the original email into separate sections. Add the following lines of code to the end of the fire
method.
/** * 執(zhí)行控制臺命令。 * * @return void */ public function fire() { // 從 stdin 讀取 $fd = fopen("php://stdin", "r"); $rawEmail = ""; while (!feof($fd)) { $rawEmail .= fread($fd, 1024); } fclose($fd); }
We first create a new parser. Next, we set the original email to the text of the parser, and finally, we call various different methods to get the data from the header or body.
You can now easily store emails in your database. For example, if you have an email entity, you can save the email to your database like this:
"messaged/php-mime-mail-parser": "dev-master"
Processing attachments
You may even want to store any attachments attached to your email on your server. The email parser class can handle any available attachments. First, add the following lines again to the top of the app/command/EmailParserCommand.php
class.
use MimeMailParser\Parser;
Now we have to extend our fire
method:
composer create-project laravel/laravel your-project-name --prefer-dist
Let's see what this part actually does. The first line retrieves the attachment from the email. $attachments
A variable is an array of attachment objects. Next, we make sure to create a new FileSystem object that will handle saving the file on our server. Then we start iterating over all attachments. We call the put
method of the FileSystem object, which accepts the path and content of the file. In this case, we want to add the file to the public/uploads
directory and use the file name the attachment actually has. The second parameter is the content of the actual file.
That's it! Your files are now stored in public/uploads
. Just make sure your mail server can actually add files to this directory by setting the correct permissions.
Configure our mail server
So far, we have prepared the entire app to retrieve, split and save our emails. However, if you don't know how to actually send the email to your newly created Artisan command, this code is useless.
Below you will find different ways to deliver email to your application, depending on the tool or mail server you are using. For example, I want to forward support@peternijssen.nl
to my app, which is located at /var/www/supportcenter
.
Note that in the actual commands you will see below, I added --env=local
every time to make sure Artisan runs like we do on the development machine. If you are in a production environment, you can delete this section.
CPanel
If you are using CPanel, you can click on the forwarder in the general menu. Add a new forwarder and define the address you want to forward to your application. Click Advanced Settings and select the Pipe to Programs option. In the input field, you can insert the following line:
php artisan command:make EmailParserCommand
Note that CPanel uses a path relative to your home directory.
Exim
If on Exim, open the file /etc/valiases/peternijssen.nl
.
Make sure the following lines exist in this file:
/** * 控制臺命令名稱。 * * @var string */ protected $name = 'email:parse'; /** * 控制臺命令描述。 * * @var string */ protected $description = '解析傳入的電子郵件。';
Run newaliases
to rebuild the alias database.
Postfix
On Postfix, make sure that before continuing, the following lines exist in your /etc/postfix/main.cf
file and are not commented:
/** * 執(zhí)行控制臺命令。 * * @return void */ public function fire() { // 從 stdin 讀取 $fd = fopen("php://stdin", "r"); $rawEmail = ""; while (!feof($fd)) { $rawEmail .= fread($fd, 1024); } fclose($fd); }
If you have to change the file, reload postfix by running service postfix reload
.
We can now create a new alias that will be passed to our application.
Open /etc/aliases
and add the following line:
"messaged/php-mime-mail-parser": "dev-master"
Run newaliases
to rebuild the alias database.
Sendmail
With Sendmail, you should first create an alias in the /etc/aliases
file:
use MimeMailParser\Parser;
Run newaliases
to rebuild the alias database. Next, make sure the chmod of the Artisan file is 755 so that it can be executed.
Finally, symlink the artisan file and php itself to /etc/smrsh
composer create-project laravel/laravel your-project-name --prefer-dist
QMail
Depending on your installation, you must ensure that the following files exist:
php artisan command:make EmailParserCommand
or:
/** * 控制臺命令名稱。 * * @var string */ protected $name = 'email:parse'; /** * 控制臺命令描述。 * * @var string */ protected $description = '解析傳入的電子郵件。';
Open any file and add the following line as content:
/** * 執(zhí)行控制臺命令。 * * @return void */ public function fire() { // 從 stdin 讀取 $fd = fopen("php://stdin", "r"); $rawEmail = ""; while (!feof($fd)) { $rawEmail .= fread($fd, 1024); } fclose($fd); }
Conclusion
Any framework with available command line tools is able to process your emails. The code provided here is just a basic setup. Depending on your project, you may just want to allow certain email addresses to send emails to your app. Before passing to your application, make sure you have filtered your emails in tools like postfix.
If you want to use some kind of ticketing system, you can easily try to extract a support ticket ID from an email subject and perform multiple different actions on the email based on that ID.
Keep attention to the log files of the mail server. It gives you some tips when the actual pipeline fails in how to resolve it.
(Due to space limitations, part of the FAQs is omitted. The original FAQs content is weakly related to the topic of the article, and some of the content is duplicated with the content of the article, so no pseudo-original processing is performed.)
The above is the detailed content of Piping Emails to a Laravel Application. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

ToversionaPHP-basedAPIeffectively,useURL-basedversioningforclarityandeaseofrouting,separateversionedcodetoavoidconflicts,deprecateoldversionswithclearcommunication,andconsidercustomheadersonlywhennecessary.StartbyplacingtheversionintheURL(e.g.,/api/v

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

Proceduralandobject-orientedprogramming(OOP)inPHPdiffersignificantlyinstructure,reusability,anddatahandling.1.Proceduralprogrammingusesfunctionsorganizedsequentially,suitableforsmallscripts.2.OOPorganizescodeintoclassesandobjects,modelingreal-worlden

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.
