Gilly
Gilly

Reputation: 9692

PHPMailer default configuration SMTP

I know how to use SMTP with PHPMailer:

$mail             = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Host       = "mail.yourdomain.com"; // sets the SMTP server
$mail->Username   = "yourname@yourdomain"; // SMTP account username
$mail->Password   = "yourpassword";        // SMTP account password

And it works fine. But my question is:

How can I configure PHPMailer to use these settings on default, so that I do not have to specify them each time I want to send mail?

Upvotes: 10

Views: 18508

Answers (3)

Liam Bailey
Liam Bailey

Reputation: 5905

You can also use this hook:

 /**
     * Fires after PHPMailer is initialized.
     *
     * @since 2.2.0
     *
     * @param PHPMailer &$phpmailer The PHPMailer instance, passed by reference.
     */
    do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );

From the source of the wp_mail function itself to modify the phpmailer class directly.

Upvotes: 0

nickstaw
nickstaw

Reputation: 309

Can I not just edit the class.phpmailer.php file?

It's best not to edit class files themselves because it makes the code harder to maintain.

Upvotes: 2

Dutow
Dutow

Reputation: 5668

Create a function, and include / use it.

function create_phpmailer() {
  $mail             = new PHPMailer();
  $mail->IsSMTP(); // telling the class to use SMTP
  $mail->SMTPAuth   = true;                  // enable SMTP authentication
  $mail->Host       = "mail.yourdomain.com"; // sets the SMTP server
  $mail->Username   = "yourname@yourdomain"; // SMTP account username
  $mail->Password   = "yourpassword";        // SMTP account password
  return $mail;
}

And call create_phpmailer() to create a new PHPMailer object.

Or you can derive your own subclass, which sets the parameters:

class MyMailer extends PHPMailer {
  public function __construct() {
    parent::__construct();
    $this->IsSMTP(); // telling the class to use SMTP
    $this->SMTPAuth   = true;                  // enable SMTP authentication
    $this->Host       = "mail.yourdomain.com"; // sets the SMTP server
    $this->Username   = "yourname@yourdomain"; // SMTP account username
    $this->Password   = "yourpassword";        // SMTP account password
  }
}

and use new MyMailer().

Upvotes: 18

Related Questions