How to set wordpress smtp without plugin?

SMTP is needed when wordpress fails to send email or delay to send emails or unable to deliver emails to inbox.

SMTP stands for Simple Mail Transfer Protocol. According to wikipedia “The Simple Mail Transfer Protocol is a communication protocol for electronic mail transmission. As an Internet standard, SMTP was first defined in 1982 by RFC 821, and updated in 2008 by RFC 5321 to Extended SMTP additions, which is the protocol variety in widespread use today.”

Question is why wordpress unable to send emails without smtp. This is not wordpres issue. Some web hosting provider like digitalocean, aws, google cloud, linode block outgoing smtp port to prevent spam. Some poor web hosting has bad reputation and email provider like gmail, yahoo block them. But best web hosting provider like siteground, a2hosting strictly keep their reputation and no need to use smtp when you host your site with them.

First of all, if we take a look at implementation of wp_mail function, we will see that this function uses PHPMailer class to send emails. Also we could notice that there is hard coded function call $phpmailer->IsMail();, which sets to use PHP’s mail() function. It means that we can’t use SMTP settings with it. We need to call isSMTP function of PHPMailer class. And also we need to set our SMTP settings as well.

To achieve it we need to get access to $phpmailer variable. And here we come to phpmailer_init action which is called before sending an email. So we can do what we need by writing our action handler:

add_action( 'phpmailer_init', 'wpse8170_phpmailer_init' );
function wpse8170_phpmailer_init( PHPMailer $phpmailer ) {
    $phpmailer->Host = 'your.smtp.server.here';
    $phpmailer->Port = 25; // could be different
    $phpmailer->Username = '[email protected]'; // if required
    $phpmailer->Password = 'yourpassword'; // if required
    $phpmailer->SMTPAuth = true; // if required
    // $phpmailer->SMTPSecure = 'ssl'; // enable if required, 'tls' is another possible value

    $phpmailer->IsSMTP();
}

 This 10 lines of code can substitute an entire SMTP plugin

How to test if smtp is working?

Go to wordpress login page, click on lost password link. Enter your email and press submit. You will get an email. Look at the source of that email.

Where to get smtp?

You can use gmail or gsuite as smtp. There are many smtp provider. Below are some best smtp provider:

  1. Sendgrid
  2. Mailgun
  3. Amazon SES
  4. Sendinblue

Leave a Reply

Your email address will not be published. Required fields are marked *