1

I'm using the phpmailer library. To send an email I need to specify an smtp server, smtp user and smtp password. The problem is I'm using the cloud platform Heroku where I use a github repository to autodeploy to heroku, I don't want my smtp username and password to be public. Is there a way to solve this?

Below is the code snippet

  $mail = new PHPMailer(false); // Passing `true` enables exceptions

    //Server settings
    //$mail->SMTPDebug = 1;//Enable verbose debug output
    $mail->isSMTP();//Set mailer to use SMTP
    $mail->Host = 'smtp host';//Specify main and backup SMTP servers
    $mail->SMTPAuth = true;//Enable SMTP authentication
    $mail->Username = 'user';//SMTP username
    $mail->Password = 'password';//SMTP password
    $mail->SMTPSecure = 'tls';//Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;//TCP port to connect to


    //Recipients
    $mail->setFrom('example@example.com','myapp');
    $mail->addAddress('hi@examle.com');//Add a recipient
    //$mail->addAddress('ellen@example.com');//Name is optional
    $mail->addReplyTo('support@example.com','Contact');



    //Content
    $mail->isHTML(true);//Set email format to HTML
    $mail->Subject = 'test';

    $mail->Body    = 'this is a test';


    $mail->send();
Vineeth Guna
  • 388
  • 4
  • 10
Cesar Augusto
  • 268
  • 4
  • 16

2 Answers2

3

One way to not expose but to use it in your code, is by setting your SMTP username and password in environment variables

The procedure to set environment variables for your heroku app is documented in this link - https://devcenter.heroku.com/articles/config-vars

Once you have set your username and password in your environment variables you can access them using the below code

    $mail->isSMTP();//Set mailer to use SMTP
    $mail->Host = 'smtp host';//Specify main and backup SMTP servers
    $mail->SMTPAuth = true;//Enable SMTP authentication
    //Assuming SMTP_USERNAME is your environment variable which holds username
    $mail->Username = getenv('SMTP_USERNAME');
    //Assuming SMTP_PASSWORD is your environment variable which holds password
    $mail->Password = getenv('SMTP_PASSWORD');
    $mail->SMTPSecure = 'tls';//Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;//TCP port to connect to

References - Use Heroku config vars with PHP?

Vineeth Guna
  • 388
  • 4
  • 10
1

There are many possible ways-

  1. Use Heroku CLI https://devcenter.heroku.com/categories/command-line

  2. You can create an admin page in you website from where you put smtp serve details that will persist to a file. This file will be available until the heroku dyno restart.

  3. You can use dropbox for deployment
  4. Instead of Github you can use bitbucket which is also free with git repo https://confluence.atlassian.com/bitbucket/deploy-to-heroku-872013667.html
Mata Prasad Chauhan
  • 554
  • 2
  • 6
  • 15