Skip to content

Instantly share code, notes, and snippets.

@khalidahmada
Created August 10, 2018 11:14
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save khalidahmada/74c3ba52e7d179e323b30d97f4847ec6 to your computer and use it in GitHub Desktop.
Save khalidahmada/74c3ba52e7d179e323b30d97f4847ec6 to your computer and use it in GitHub Desktop.
Config Wordpress SMTP for MailHog - test your emails local
/*
* Add the MailHog to your wordpress projects
* By Khalid Ahmada
* MailHog @see https://github.com/mailhog/MailHog
*/
class WP_MAILHOG
{
function __construct()
{
// Config only on local
if ($this->isLocal()) {
$this->AddSMTP();
}
}
/**
* Config Your local rule
* default is check if the host is *.test or *.local
* @return bool
*/
private function isLocal()
{
if (defined('WP_HOME')) {
if (strpos(WP_HOME, '.test') !== false ||
strpos(WP_HOME, '.local') !== false
) {
return true;
}
}
return false;
}
/*
* Wordpress default hook to config php mail
*/
private function AddSMTP()
{
add_action('phpmailer_init', array($this, 'configEmailSMTP'));
}
/*
* Config MailTramp SMTP
*/
public function configEmailSMTP(PHPMailer $phpmailer)
{
$phpmailer->IsSMTP();
$phpmailer->Host='127.0.0.1';
$phpmailer->Port=1025;
$phpmailer->Username='';
$phpmailer->Password='';
$phpmailer->SMTPAuth=true;
}
}
new WP_MAILHOG();
@khalidahmada
Copy link
Author

This is my snippet based on MailHog you need first to install MailHog and then configure it just need the add the next snippet into your functions.php

https://gist.github.com/khalidahmada/74c3ba52e7d179e323b30d97f4847ec6

Please note that you need the configure your rule that checks if turn on local or not by default rule tests the constant 'WP_HOME' into your wp-config.php if contains 'test' or 'local' either that you need to specify your own role rule the function in the snippet it's isLocal()

@s1awek
Copy link

s1awek commented Jul 17, 2023

Thanks for the snippet, but it gives me following error:
PHP Fatal error: Uncaught TypeError: WP_MAILHOG::configEmailSMTP(): Argument #1 ($phpmailer) must be of type PHPMailer, PHPMailer\PHPMailer\PHPMailer given

@s1awek
Copy link

s1awek commented Jul 17, 2023

Just found the solution:

    public function configEmailSMTP(PHPMailer\PHPMailer\PHPMailer $phpmailer)
    {
        $phpmailer->IsSMTP();
        $phpmailer->Host = '127.0.0.1';
        $phpmailer->Port = 1025;
        $phpmailer->Username = '';
        $phpmailer->Password = '';
        $phpmailer->SMTPAuth = true;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment