Skip to content
← Back to Snippets
Code

Send Basic Email with mail()

Validates a recipient and subject, builds simple text headers, and sends a basic email through mail() only when inputs are valid.

Purpose

Validates a recipient and subject, builds simple text headers, and sends a basic email through mail() only when inputs are valid.

Snippet details

ContextEmailLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Send Basic Email with mail().
 *
 * Purpose:
 * Sends a plain text email after validating the recipient and subject.
 *
 * @param string $to Recipient email address.
 * @param string $subject Email subject.
 * @param string $message Plain text message.
 * @param string $from Sender email address.
 * @return array Send result.
 */
function ogSnippetSendBasicEmail(string $to, string $subject, string $message, string $from): array {
	$result = array(
		'ok' => false,
		'message' => 'Email was not sent.'
	);

	$to = trim($to);
	$subject = trim($subject);
	$message = trim($message);
	$from = trim($from);

	if (filter_var($to, FILTER_VALIDATE_EMAIL) === false) {
		$result['message'] = 'Recipient email is invalid.';
		return $result;
	}

	if (filter_var($from, FILTER_VALIDATE_EMAIL) === false) {
		$result['message'] = 'Sender email is invalid.';
		return $result;
	}

	if ($subject === '' || $message === '') {
		$result['message'] = 'Subject and message are required.';
		return $result;
	}

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

	if (mail($to, $subject, $message, $headers) === true) {
		$result['ok'] = true;
		$result['message'] = 'Email was sent.';
	}

	return $result;
}

$email_result = ogSnippetSendBasicEmail('', 'Stargate Report', 'Chevron seven locked.', 'noreply@example.com');

echo 'Email result: '.$email_result['message'];