📧 Complete Guide: Integrating SendGrid with Open-source MediaWiki for Reliable Email Delivery

📧 Complete Guide: Integrating SendGrid with Open-source MediaWiki for Reliable Email Delivery

MediaWiki’s default email functionality often faces deliverability issues, especially in production environments where emails may end up in spam folders or fail to send entirely.

SendGrid, a cloud-based email delivery service, provides a robust solution with advanced features like analytics, bounce handling, and reputation management.

This guide walks you through integrating SendGrid with MediaWiki, covering common challenges and their solutions.

🔹 Why SendGrid for MediaWiki?

❌ Common MediaWiki Email Problems

  • Poor Deliverability – Emails often land in spam
  • No Tracking – No insight into delivery status
  • Server Dependencies – Requires complex SMTP setup
  • Rate Limiting – Hosting providers limit email sending
  • No Bounce Handling – No automated email validation

✅ SendGrid Benefits

  • High Deliverability (99%+ inbox rates)
  • Scalability – Thousands of emails/hour
  • Analytics – Opens, clicks, bounces, spam reports
  • Reliability – Enterprise-grade infrastructure
  • Easy Integration – API or SMTP
  • Compliance – CAN-SPAM & GDPR ready

🔹 Prerequisites

Before starting, ensure you have:

  1. MediaWiki 1.35+ installed
  2. A SendGrid account (free tier available)
  3. Verified sender domain in SendGrid
  4. PHP cURL extension enabled
  5. Admin access to MediaWiki


🔹 Step 1: SendGrid Setup

1.1 Create SendGrid Account

  • Sign up at SendGrid.com
  • Verify your email
  • Complete onboarding

1.2 Domain Authentication

Add these DNS records:

CNAME: s1._domainkey.yourdomain.com → s1.domainkey.u12345.wl.sendgrid.net
CNAME: s2._domainkey.yourdomain.com → s2.domainkey.u12345.wl.sendgrid.net
CNAME: em1234.yourdomain.com       → u12345.wl.sendgrid.net
        

1.3 Create API Key

  • Navigate to Settings → API Keys
  • Create key with Mail Send permissions
  • Save it securely


🔹 Step 2: Build a SendGrid Extension

Create directory structure:

extensions/SendGrid/
├── extension.json
├── includes/
│   ├── SendGridHooks.php
│   └── SendGridMailer.php
├── i18n/
│   └── en.json
├── test-email.php
└── README.md
        

Example: SendGridMailer.php

class SendGridMailer {
    public function send($to, $from, $subject, $body, $headers = []) {
        global $wgSendGridAPIKey, $wgSendGridFromEmail, $wgSendGridFromName;

        $toEmail = is_array($to) ? $to[0]->address : $to->address;
        $fromEmail = $wgSendGridFromEmail ?: $from->address;

        $data = [
            'personalizations' => [[
                'to' => [['email' => $toEmail]]
            ]],
            'from' => ['email' => $fromEmail, 'name' => $wgSendGridFromName],
            'subject' => $subject,
            'content' => [[
                'type' => 'text/html',
                'value' => $body
            ]]
        ];

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'https://api.sendgrid.com/v3/mail/send',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $wgSendGridAPIKey,
                'Content-Type: application/json'
            ],
            CURLOPT_RETURNTRANSFER => true
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $httpCode == 202;
    }
}
        

🔹 Step 3: Configure MediaWiki In LocalSettings.php:

# Enable email
$wgEnableEmail = true;
$wgEnableUserEmail = true;

# Load SendGrid extension
wfLoadExtension('SendGrid');

# SendGrid Config
$wgSendGridAPIKey = 'YOUR_SENDGRID_API_KEY';
$wgSendGridFromEmail = 'noreply@yourdomain.com';
$wgSendGridFromName = 'Your Wiki';
        

👉 Use environment variables instead of hardcoding API keys:

$wgSendGridAPIKey   = getenv('SENDGRID_API_KEY');
$wgSendGridFromEmail = getenv('SENDGRID_FROM_EMAIL');
        

🔹 Step 4: Testing Run test script:

php extensions/SendGrid/test-email.php --to=test@example.com
        

Test password reset via:

Special:PasswordReset
        

🔹 Step 5: Common Issues

❌ API Key Not Working

  • Check logs: var_dump($wgSendGridAPIKey)
  • Test with curl against SendGrid

❌ Emails Going to Spam

  • Add SPF & DKIM records
  • Use a verified domain
  • Avoid free email addresses (e.g., Gmail, Yahoo)

❌ Rate Limiting

Implement small delays between sends


🔹 Step 6: Best Practices

  • 🔒 Use environment variables for API keys
  • 🛑 Disable debugging in production
  • 📊 Monitor logs + SendGrid dashboard
  • ⚡ Optimize with connection pooling


🔹 Step 7: Advanced Features

  • Custom Email Templates for branding
  • Bounce Handling via SendGrid webhooks
  • Analytics & Tracking built-in


✅ Conclusion

By integrating SendGrid with MediaWiki you unlock:

  • 99%+ email deliverability
  • Real-time tracking (opens, bounces, spam)
  • Enterprise-grade scalability
  • Automatic compliance & reputation management

This solution has been tested in production on large MediaWiki deployments, handling thousands of daily emails with excellent reliability.


📚 Resources


🔔 If you found this useful, consider sharing it with others working on MediaWiki deployments!

Twilio SendGrid Partner - Caddycode MediaWiki #SendGrid #MediaWiki

To view or add a comment, sign in

More articles by Syed Asad Raza

Others also viewed

Explore content categories