Skip to content

Instantly share code, notes, and snippets.

@ePirat
Created May 12, 2026 01:00
Show Gist options
  • Select an option

  • Save ePirat/c0d2c58a64e3e7e91ddff56ea2deae14 to your computer and use it in GitHub Desktop.

Select an option

Save ePirat/c0d2c58a64e3e7e91ddff56ea2deae14 to your computer and use it in GitHub Desktop.
Simple Wordpress mail settings plugin
<?php
/*
* Plugin Name: SMTP Mail Setup
*/
// Error when called directly
if (!defined('ABSPATH')) {
die();
}
// Return env variable or return default value
function get_env_value($env, $default) {
$value = getenv($env);
if ($value !== false) {
return $value;
}
return $default;
}
// Return value from env_FILE or fallback to env value or default
function get_env_value_file($env, $default) {
$filename = getenv($env . '_FILE');
if ($filename !== false) {
$content = file_get_contents($filename);
if ($content !== false) {
return rtrim($content, "\r\n");
}
}
return get_env_value($env, $default);
}
function mailer_filter_custom_wp_mail_from( $address ) {
$smtp_from = get_env_value("MAILER_SMTP_FROM", '');
if (!empty($smtp_from))
return $smtp_from;
return $address;
}
function mailer_custom_phpmailer_init( $phpmailer ) {
$smtp_host = get_env_value("MAILER_SMTP_HOST", '');
if (empty($smtp_host)) {
return;
}
$smtp_port = get_env_value("MAILER_SMTP_PORT", 465);
$smtp_user = get_env_value_file("MAILER_SMTP_USER", '');
$smtp_pass = get_env_value_file("MAILER_SMTP_PASS", '');
$smtp_starttls = get_env_value("MAILER_SMTP_STARTTLS", false);
// Send using SMTP
$phpmailer->isSMTP();
$phpmailer->Host = $smtp_host;
$phpmailer->Port = $smtp_port;
if (!empty($smtp_user) || !empty($smtp_pass)) {
$phpmailer->SMTPAuth = true;
if (!empty($smtp_user)) {
$phpmailer->Username = $smtp_user;
}
if (!empty($smtp_pass)) {
$phpmailer->Password = $smtp_pass;
}
}
$phpmailer->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
if (filter_var($smtp_starttls, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
$phpmailer->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
}
}
add_action( 'phpmailer_init', 'mailer_custom_phpmailer_init' );
add_filter( 'wp_mail_from', 'mailer_filter_custom_wp_mail_from' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment