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?
Log in to SendGrid: https://app.sendgrid.com.
Go to Settings > Inbound Parse.
Click "Add Hostname" and enter your domain (e.g., mail.yourdomain.com
).
Set the POST URL to your PHP script (e.g., https://yourwebsite.com/inbound-email.php
).
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!";
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With