Core points
php artisan email:parse
, which can be registered and executed in Artisan to retrieve the original message from the IO stream. 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. 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.
/** * 执行控制台命令。 * * @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.
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.
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.
On Postfix, make sure that before continuing, the following lines exist in your /etc/postfix/main.cf
file and are not commented:
/** * 执行控制台命令。 * * @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.
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
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:
/** * 执行控制台命令。 * * @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!