Home > Backend Development > PHP Tutorial > Piping Emails to a Laravel Application

Piping Emails to a Laravel Application

Joseph Gordon-Levitt
Release: 2025-02-22 10:34:10
Original
599 people have browsed it

Piping Emails to a Laravel Application

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
Copy after login
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login
Copy after login

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 = '解析传入的电子邮件。';
Copy after login
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login
Copy after login

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 = '解析传入的电子邮件。';
Copy after login
Copy after login
Copy after login
Copy after login

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);
}
Copy after login
Copy after login
Copy after login

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"
Copy after login
Copy after login

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;
Copy after login
Copy after login

Now we have to extend our fire method:

composer create-project laravel/laravel your-project-name --prefer-dist
Copy after login
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login
Copy after login

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 = '解析传入的电子邮件。';
Copy after login
Copy after login
Copy after login
Copy after login

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:

/**
 * 执行控制台命令。
 *
 * @return void
 */
public function fire()
{
    // 从 stdin 读取
    $fd = fopen("php://stdin", "r");
    $rawEmail = "";
    while (!feof($fd)) {
        $rawEmail .= fread($fd, 1024);
    }
    fclose($fd);
}
Copy after login
Copy after login
Copy after login

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"
Copy after login
Copy after login

Run newaliases to rebuild the alias database.

Sendmail

With Sendmail, you should first create an alias in the /etc/aliases file:

use MimeMailParser\Parser;
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login
Copy after login

QMail

Depending on your installation, you must ensure that the following files exist:

php artisan command:make EmailParserCommand
Copy after login
Copy after login
Copy after login
Copy after login

or:

/**
 * 控制台命令名称。
 *
 * @var string
 */
protected $name = 'email:parse';

/**
 * 控制台命令描述。
 *
 * @var string
 */
protected $description = '解析传入的电子邮件。';
Copy after login
Copy after login
Copy after login
Copy after login

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);
}
Copy after login
Copy after login
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template