Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sendgrid parse webhook - email forwarding

I am having a PHP web application with SendGrid integration for both incoming (parse webhook) and outcoming mail (PHP mail() with system configuration for mail proxy). Currently our incoming mail system consists of an endpoint, which saves all contact emails to our database. We want also to have some direct email forwarding mappings to other mail providers (like [email protected] => [email protected]).

As far as I know, there is no routing of email or forwarding them with SMTP protocol in SendGrid's side, only plain API calls connecting to our endpoint. Creating MX records pointing to our IP address is not an option, as we don't want to reveal our servers' origin IP address to the public (DDoS risk).

Should I just write code to get the contents of email and mail() it forward? Some data will be missing, but for the most part it should work. Or is there a way to connect something like a Gmail Business account to listen for mails for these specific addresses?

like image 845
hegez Avatar asked Sep 05 '25 02:09

hegez


1 Answers

Step 1: Set Up SendGrid Inbound Parse Webhook

  1. Log in to SendGrid: https://app.sendgrid.com.

  2. Go to Settings > Inbound Parse.

  3. Click "Add Hostname" and enter your domain (e.g., mail.yourdomain.com).

  4. Set the POST URL to your PHP script (e.g., https://yourwebsite.com/inbound-email.php).

  5. Update your MX records to point to SendGrid.

<?php
// Read the raw POST data from SendGrid
$raw_post_data = file_get_contents("php://input");

// If JSON format, decode it
$parsed_data = json_decode($raw_post_data, true);

if (!$parsed_data) {
    // If not JSON, fallback to $_POST (form-data)
    $parsed_data = $_POST;
}

// Extract email details
$from = $parsed_data['from'] ?? '[email protected]';
$to = $parsed_data['to'] ?? '';
$subject = $parsed_data['subject'] ?? 'No Subject';
$text = $parsed_data['text'] ?? 'No message content';
$html = $parsed_data['html'] ?? '';

// File attachments (if any)
$attachments = $_FILES ?? [];

// Forward email to another recipient
$forwardTo = "[email protected]"; // Change to your recipient email

$headers = "From: " . $from . "\r\n" .
           "Reply-To: " . $from . "\r\n" .
           "Content-Type: text/html; charset=UTF-8\r\n";

// Forward the email
mail($forwardTo, "FWD: " . $subject, $html ?: nl2br($text), $headers);

echo "Email forwarded successfully!";
?>
like image 71
Parag Sharma Avatar answered Sep 07 '25 13:09

Parag Sharma