Created
August 10, 2018 11:14
-
-
Save khalidahmada/74c3ba52e7d179e323b30d97f4847ec6 to your computer and use it in GitHub Desktop.
Config Wordpress SMTP for MailHog - test your emails local
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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(); |
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
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
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 yourwp-config.php
if contains'test'
or'local'
either that you need to specify your own role rule the function in the snippet it'sisLocal()