我将使用 PHP 发送电子邮件。我的 PHP 应该在共享主机上。我找到了 codes通过 PHP 发送电子邮件,但我担心将直接密码写入 PHP 代码。 PHP 或 GMail SMTP 服务器是否提供任何方法来避免使用直接密码?也许类似于 API 身份验证?
最佳答案
我从来没有真正尝试过将电子邮件发送到 SMTP 服务器(例如 google),因为所有这些服务都需要身份验证。 Github 中有一些很棒的项目,例如 this , 这允许使用安全端口、身份验证、SSL 等通过 SMTP 发送电子邮件。(请记住,php 文件是服务器端的,因此用户无法访问此信息。因此您的传递是安全的。)
如果你访问他们的 repo,你会找到他们的样本:
<?php
require 'class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'jswan'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'from@example.com';
$mail->FromName = 'Mailer';
$mail->AddAddress('josh@example.net', 'Josh Adams'); // Add a recipient
$mail->AddAddress('ellen@example.com'); // Name is optional
$mail->AddReplyTo('info@example.com', 'Information');
$mail->AddCC('cc@example.com');
$mail->AddBCC('bcc@example.com');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->AddAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->AddAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$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->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
但是如果你不想在 php Controller 上硬编码密码或者你必须使用什么来处理电子邮件,你总是可以使用 mail()在 php 上发送电子邮件的功能。
在文档中轻松找到示例:
<?php
$to = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
此功能是发送电子邮件的 SMTP 方式,但始终需要身份验证,但在这种情况下,它是通过服务器进行的,因此必须设置所有 header 才能发送正确的电子邮件。
请注意,一些服务器提供商不会大声发送电子邮件以实现此功能,因此最后您将需要创建或使用 php SMTP 电子邮件类来处理电子邮件,并且出于身份验证原因,此文件必须具有密码。
关于php - GMail SMTP 避免在 PHP 代码中使用直接密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17230438/