Skip to content
Advertisement

Using global variables in PHPMailer

Instead of this:

$mail->isSMTP();  
$mail->Host = 'smtp.demo-server.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 'demo-port';
$mail->Username = 'demo-email@gmail.com'; 
$mail->Password = 'demo-password';

I would like to keep the values in a separate file and use variables instead:

$mail->isSMTP();  
$mail->Host = echo $server; // also tried without echo
$mail->SMTPAuth = true;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = echo $port;
$mail->Username = echo $username; 
$mail->Password = echo $password;

I’m already using output buffering, have set the global scope, and the variable values contain the quotes. Still not working.

Advertisement

Answer

To begin with, kindly read @Synchro‘s comment.

  • Create a php file if you’ve not done that already (eg. mail_config.php) and declare your variables in it.
  • Require/Include the mail_config.php file in your “main” file (the file that will send the mail eg. send_mail.php).
  • Assign the PHPMailer props to their respective variables from the mail_config.php file in the send_mail.php file.

Example

mail_config.php

<?php

$server   = 'smtp.gmail.com';
$port     = 465;
$username = 'test@gmail.com';
$password = '123456';

?>

send_mail.php

<?php

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

// require the settings file. This contains the settings
require 'path/to/mail_config.php';

// require the vendor/autoload.php file if you're using Composer
require 'path/to/vendor/autoload.php';

// require phpmailer files if you're not using Composer
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host          = $server;
    $mail->SMTPAuth      = true;
    $mail->SMTPSecure    = PHPMailer::ENCRYPTION_SMTPS; // 'ssl'
    $mail->Port          = $port;
    $mail->Username      = $username;
    $mail->Password      = $password;

    $mail->setFrom('from@example.com', "Sender's Name"); // sender's email(mostly the `$username`) and name.
    $mail->addAddress('test@example.com', 'Stackoverflow'); // recipient email and optional name.

    //Content
    $mail->isHTML(true); //Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';

    $mail->send();
    echo 'Message has been sent';
} catch(Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

?>

Read more https://github.com/PHPMailer/PHPMailer

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement