Skip to content

Instantly share code, notes, and snippets.

@joychetry
Last active July 29, 2024 12:53
Show Gist options
  • Save joychetry/21df5392f82e690a012f758986f5d9b8 to your computer and use it in GitHub Desktop.
Save joychetry/21df5392f82e690a012f758986f5d9b8 to your computer and use it in GitHub Desktop.
WordPress Custom Gmail SMTP
//In functions.php
//Custom SMTP
/** Custom SMTP Settings */
function custom_phpmailer_smtp( $phpmailer ) {
$phpmailer->isSMTP();
$phpmailer->Host = SMTP_HOST;
$phpmailer->SMTPAuth = true;
$phpmailer->Port = SMTP_PORT;
$phpmailer->Username = SMTP_USER;
$phpmailer->Password = SMTP_PASS;
$phpmailer->SMTPSecure = SMTP_SECURE;
$phpmailer->From = SMTP_FROM;
$phpmailer->FromName = SMTP_NAME;
}
add_action( 'phpmailer_init', 'custom_phpmailer_smtp' );
add_action('admin_menu', 'smtp_test_email_menu');
function smtp_test_email_menu() {
add_menu_page(
'SMTP Test Email', // Page title
'SMTP Test Email', // Menu title
'manage_options', // Capability
'smtp-test-email', // Menu slug
'smtp_test_email_page' // Callback function
);
}
function smtp_test_email_page() {
?>
<div class="wrap">
<h1>Send Test Email</h1>
<?php
if (isset($_POST['send_test_email'])) {
$to = sanitize_email($_POST['to_email']);
$subject = 'SMTP Configuration Test';
$message = 'Hello,
This is a test email to confirm that your WordPress site is configured correctly to send emails using Gmail SMTP.
Best regards,<br>
<a href="https://joychetry.com">Joy Chetry</a>';
if (wp_mail($to, $subject, $message)) {
echo '<div class="notice notice-success"><p>Email sent successfully!</p></div>';
} else {
echo '<div class="notice notice-error"><p>Failed to send email.</p></div>';
}
}
?>
<form method="post">
<table class="form-table">
<tr valign="top">
<th scope="row">Recipient Email</th>
<td><input type="email" name="to_email" required /></td>
</tr>
</table>
<?php submit_button('Send Test Email', 'primary', 'send_test_email'); ?>
</form>
</div>
<?php
}
//In wp-config.php
/** Custom SMTP Settings */
define( 'SMTP_USER', 'you@gmail.com' );
define( 'SMTP_PASS', 'cfle ocgr dwrp enak' );
define( 'SMTP_HOST', 'smtp.gmail.com' );
define( 'SMTP_FROM', 'you@gmail.com' );
define( 'SMTP_NAME', 'Your Name' );
define( 'SMTP_PORT', 587 );
define( 'SMTP_SECURE', 'tls' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment