You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置仅允许特定域名的发件人邮箱发送邮件?

Restricting Sender Emails to @abc.com in PHP

Great question! To ensure only emails ending with @abc.com are allowed as the sender, you need to add two key checks before sending the email: validating the email format, and verifying the domain suffix. Here's how to implement this properly with your existing code:

Step-by-Step Implementation

  • Validate the Email Format: First, confirm the input is a valid email address using PHP's built-in filter_var function—this avoids invalid entries like invalid@@abc.com or missing@domain.
  • Check the Allowed Domain: Extract the domain part of the email and ensure it matches abc.com.

Modified Code

$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = $_POST['Sender'];

// 1. Validate email format
if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format. Please enter a valid email address.";
    exit;
}

// 2. Check if domain is @abc.com
$allowedDomain = 'abc.com';
// Extract domain by getting everything after the last "@"
$domain = substr(strrchr($from, '@'), 1);

if ($domain !== $allowedDomain) {
    echo "Only emails from the @abc.com domain are allowed.";
    exit;
}

// If validation passes, send the email
$headers = "From:" . $from;
if (mail($to, $subject, $message, $headers)) {
    echo "Mail Sent.";
} else {
    echo "Failed to send mail.";
}

Alternative: Regex Check

If you prefer a regex approach to directly check the suffix, you can replace the domain check with this:

if (!preg_match('/@abc\.com$/', $from)) {
    echo "Only emails from the @abc.com domain are allowed.";
    exit;
}

This regex ensures the email ends with @abc.com (note the escaped . since it's a special character in regex).

Important Notes

  • Always validate user input before using it in mail functions to prevent spam or misuse.
  • Adding clear error messages helps users understand why their submission was rejected.

内容的提问来源于stack exchange,提问作者Jt Tan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:17:36