SendGrid: A powerful tool for converting emails into apps
SendGrid is not only a service that sends mail in batches, it also provides a lesser-known powerful feature: processing received mail. With simple configuration, you can let SendGrid process all emails under the specified domain name and send email messages to your server. This article will introduce how to build a "mail to article" function using SendGrid.
Core points:
- SendGrid's inbound mail resolution function can process all messages from a specified domain name and send mail information to the specified URI in the form of a POST request.
- By setting up a webhook, you can customize the received emails.
- SendGrid's inbound email resolution function is widely used, such as: email arrival reminder, attachment upload to cloud storage, email reply forum notifications, processing unsubscribe requests, etc.
- SendGrid's inbound resolution Webhook supports the use of wildcard subdomains to process multiple email addresses, supports HTTPS secure data transmission, the total size of the attachment is limited to 20MB, and provides dashboard activity logs for easy debugging.
Beginner:
The sample code in this article is based on the Slim Framework framework. For easy debugging, please add the following content in the composer.json
section: require
"slim/extras": "dev-develop"Modify the framework instantiation code in
and configure the logger: include/services.php
$app = new Slim(array( 'view' => new Twig(), 'templates.path' => $c['config']['path.templates'], 'log.writer' => new \Slim\Extras\Log\DateTimeFileWriter(array( 'path' => dirname($c['config']['path.logs']), 'name_format' => 'Y-m-d', 'message_format' => '%label% - %date% - %message%' )) ));Copy the sample configuration file to
and set your configuration value (such as database connection information). Add the following code to specify the directory where the log file and upload the image: config/config.php
'path.logs' => $basedir . 'logs/', 'path.uploads' => $basedir . 'public/uploads/'Create these directories and make sure the web server has write permissions.
Our app will provide registered users with an email alias. By matching the part before the
symbol in the recipient's email address, we can determine the user who posted it. In practical applications, you may need to set more complex aliases rules and limit email sending addresses. The database structure defines two tables for storing users and articles: @
CREATE TABLE users ( id INTEGER NOT NULL AUTO_INCREMENT, name VARCHAR(128) NOT NULL , alias VARCHAR(45) NOT NULL , PRIMARY KEY (id) , INDEX alias (alias ASC) ); CREATE TABLE posts ( id INTEGER NOT NULL AUTO_INCREMENT, title VARCHAR(255) NOT NULL, body TEXT NOT NULL, image varchar(255), user_id INTEGER NOT NULL, PRIMARY KEY (id) );You need a SendGrid account (free account is sufficient). After registering, go to the developer page and click "Analyze the incoming email". Enter your hostname and callback URL.
. The specific operation depends on your hosting provider. mx.sendgrid.net
Build callback function:
Your application needs to respond to the POST request of the URL you specified, for example:"slim/extras": "dev-develop"
If SendGrid's "ping" test returns a 4xx or 5xx error, it queues the request and tries again for 3 days. Therefore, a successful ping test must return a 200 status code. SendGrid's POST request contains various information about the email, please refer to the SendGrid API documentation for details. We mainly focus on the following fields:
Because the to
field formats are diverse, we need regular expressions to parse multiple recipients:
$app = new Slim(array( 'view' => new Twig(), 'templates.path' => $c['config']['path.templates'], 'log.writer' => new \Slim\Extras\Log\DateTimeFileWriter(array( 'path' => dirname($c['config']['path.logs']), 'name_format' => 'Y-m-d', 'message_format' => '%label% - %date% - %message%' )) ));
For each recipient, extract the alias section and find the matching user:
'path.logs' => $basedir . 'logs/', 'path.uploads' => $basedir . 'public/uploads/'
Create an article:
CREATE TABLE users ( id INTEGER NOT NULL AUTO_INCREMENT, name VARCHAR(128) NOT NULL , alias VARCHAR(45) NOT NULL , PRIMARY KEY (id) , INDEX alias (alias ASC) ); CREATE TABLE posts ( id INTEGER NOT NULL AUTO_INCREMENT, title VARCHAR(255) NOT NULL, body TEXT NOT NULL, image varchar(255), user_id INTEGER NOT NULL, PRIMARY KEY (id) );
Now we have the basic "email to article" function! Next, we can add attachment processing function, allowing users to add images through email attachments. SendGrid's POST request contains the attachments
parameter, indicating the number of attachments. Attachments are POSTed together with requests, and the processing method is the same as that of uploading web form files.
$app->post('/endpoints/email', function () use ($app, $c) {
Summary:
This article introduces a simple application of SendGrid's inbound email resolution function - the "Mail to Article" function, which allows users to create articles by sending emails. Through simple callback functions, you can implement various interesting functions, such as: email arrival reminder, attachment upload to cloud storage, email reply forum notifications, processing unsubscribe requests, etc.
(The subsequent content, namely the FAQ part, is recommended to deal with it separately due to the length of the article. The FAQ part can be submitted separately as a new question.)
The above is the detailed content of Handle Incoming Email with SendGrid. 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.
