我正在使用phpmailer库。要发送电子邮件,我需要指定smtp服务器,smtp用户和smtp密码。问题是我正在使用云平台Heroku,我使用github存储库自动部署到heroku,我不希望我的smtp用户名和密码是公开的。有办法解决这个问题吗?
以下是代码段
$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('[email protected]','myapp');
$mail->addAddress('[email protected]');//Add a recipient
//$mail->addAddress('[email protected]');//Name is optional
$mail->addReplyTo('[email protected]','Contact');
//Content
$mail->isHTML(true);//Set email format to HTML
$mail->Subject = 'test';
$mail->Body = 'this is a test';
$mail->send();
一种不暴露但在代码中使用它的方法是在环境变量中设置SMTP用户名和密码
为heroku应用程序设置环境变量的过程记录在此链接中 - https://devcenter.heroku.com/articles/config-vars
在环境变量中设置用户名和密码后,可以使用以下代码访问它们
$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
有很多可能的方法 -