我在一个网站上使用PHP,我想添加电子邮件功能。

我安装了WampServer。

如何使用PHP发送电子邮件?


当前回答

你可以使用诸如邮戳、Sendgrid等邮件网络服务。

Sendgrid vs邮戳vs亚马逊SES和其他电子邮件/SMTP API提供商?

编辑:我现在只使用谷歌Gmail API。由于严格的过滤器,我在向雇主发送提醒邮件时遇到了麻烦。但只要你不发垃圾邮件,Gmail就可以工作。

其他回答

使用PHPMailer通过邮件发送用户密码的步骤:

步骤1:首先,从GitHub下载PHPMailer软件包

您只需下载PHPMailer源文件并手动包含所需的文件。

您可以从PHPMailer主页[1]下载带有源代码的ZIP文件, 点击“克隆或下载”绿色按钮(右侧),然后选择“下载ZIP”。 在要保存源文件的目录中解压缩包。

[1] https://github.com/PHPMailer/PHPMailer

第二步:打开“(来自Gmail地址)谷歌帐户”,执行以下步骤:

禁用谷歌帐号的双因素密码验证。 打开Less Security。 允许第三方应用程序。

步骤3:尝试使用下面的代码(注意:在这里,我只提供了使用PHP和MySQL通过电子邮件发送用户密码的功能代码)


    <?php 
    session_start();

    use PHPMailer\PHPMailer\PHPMailer;  //add use in starting of the code

    $db = mysqli_connect('localhost', 'root', '', '[Enter your Database Name]'); // connect to database

    if (isset($_POST['forgot_btn'])) {
        forgotpassword();
    }

    function forgotpassword(){
    global $db;
     
        $user_id = $_POST['user_id'];
        $result = mysqli_query($db,"SELECT * FROM users where user_id='$user_id'");
        $row = mysqli_fetch_assoc($result);
        $fetch_user_id=$row['user_id'];
        $name=$row['name'];
        $email_id=$row['email_id'];
        $password=$row['password'];
        if($user_id==$fetch_user_id) {
       require '../PHPMailer/vendor/autoload.php';  //Please correctly mention the PHPMailer installed directory (Don't follow my directory)

    $mail = new PHPMailer(TRUE);
    try{
       $mail->setFrom('[Enter your From Email_Address]', '[Enter Sender Name]');
       $mail->addAddress($email_id, $name);  //[To Email Address and Name]
       $mail->Subject = 'Regarding Forgot Password';
       $mail->Body = 'Hi '.$name.',Your Login Password is:'.$password.'';
       $mail->isSMTP();
       $mail->Host = 'smtp.gmail.com';
       $mail->SMTPAuth = TRUE;
       $mail->SMTPSecure = 'tls';
       $mail->Username = '[Enter your From Email_Address]';
       $mail->Password = '[Enter your From Email_Address -> Password]';
       $mail->Port = 587;
       
       if($mail->send())
       {
          echo "<script>alert('Password Sent Successfully');</script>"; 
       }
       else
       {
         echo "<script>alert('Please Check Your Internet Connection or From Email Address/Password or Wrong To Email Address');</script>";   
       }
    }
    catch (Exception $e)
    {
       echo "<script>alert('Please Check Your Internet Connection or From Email Address/Password or Wrong To Email Address');</script>";
    }
        }
    }

    ?>

更多信息请参考这些文档[1]:

[1]. https://alexwebdevelop.com/phpmailer-tutorial/

对于未来的读者:如果其他答案都不管用(就像我的情况一样),试试这个:

1)。下载PHPMailer,打开zip文件并解压到您的项目目录。

3)。将提取的目录重命名为phpailer,并在php脚本中编写以下代码(脚本必须在phpailer文件夹之外)

<?php
// PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer; 
use PHPMailer\PHPMailer\Exception;
// Base files 
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
// create object of PHPMailer class with boolean parameter which sets/unsets exception.
$mail = new PHPMailer(true);                              
try {
    $mail->isSMTP(); // using SMTP protocol                                     
    $mail->Host = 'smtp.gmail.com'; // SMTP host as gmail 
    $mail->SMTPAuth = true;  // enable smtp authentication                             
    $mail->Username = 'sender@gmail.com';  // sender gmail host              
    $mail->Password = 'password'; // sender gmail host password                          
    $mail->SMTPSecure = 'tls';  // for encrypted connection                           
    $mail->Port = 587;   // port for SMTP     

    $mail->setFrom('sender@gmail.com', "Sender"); // sender's email and name
    $mail->addAddress('receiver@gmail.com', "Receiver");  // receiver's email and name

    $mail->Subject = 'Test subject';
    $mail->Body    = 'Test body';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) { // handle error.
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>
<?php
include "db_conn.php";//connection file
require "PHPMailerAutoload.php";// it will be in PHPMailer
require "class.smtp.php";// it will be in PHPMailer
require "class.phpmailer.php";// it will be in PHPMailer


$response = array();
$params = json_decode(file_get_contents("php://input"));

if(!empty($params->email_id)){

    $email_id = $params->email_id;
    $flag=false;
    echo "something";
    if(!filter_var($email_id, FILTER_VALIDATE_EMAIL))
    {
        $response['ERROR']='EMAIL address format error'; 
        echo json_encode($response,JSON_UNESCAPED_SLASHES);
        return;
    }
    $sql="SELECT * from sales where email_id ='$email_id' ";

    $result = mysqli_query($conn,$sql);
    $count = mysqli_num_rows($result);

    $to = "demo@gmail.com";
    $subject = "DEMO Subject";
    $messageBody ="demo message .";

    if($count ==0){
        $response["valid"] = false;
        $response["message"] = "User is not registered yet";
        echo json_encode($response);
        return;
    }

    else {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true; // authentication enabled
        $mail->IsHTML(true); 
        $mail->SMTPSecure = 'ssl';//turn on to send html email
        // $mail->Host = "ssl://smtp.zoho.com";
        $mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail 
        $mail->Port = 465;
        $mail->Username = "demousername@example.com";
        $mail->Password = "demopassword";
        $mail->SetFrom("demousername@example.com", "Any demo alert");
        $mail->Subject = $subject;

        $mail->Body = $messageBody;
        $mail->AddAddress($to);
        echo "yes";

        if(!$mail->send()) {
           echo "Mailer Error: " . $mail->ErrorInfo;
       } 
       else {
           echo "Message has been sent successfully";
      }
    }

}
else{
    $response["valid"] = false;
    $response["message"] = "Required field(s) missing";
    echo json_encode($response);
}


?>

上面的代码为我工作。

   $emailTextHtml='<h1>email sent from php use by phpmailer</h1>';

require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer(true);                          // Passing `true` enables exceptions
try {
    //Server settings
    //$mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'demo@gmail.com';                 // SMTP username of gmail
    $mail->Password = '2345678';                           // SMTP password of gmail
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('anupam@gmail.com', 'study'); // provide your gmail username 
    $mail->addAddress('komal@gmail.com', 'study');     // Add a recipient
    $mail->addReplyTo('anupamverma@gmail.com', 'Information');

    //Content
    $mail->isHTML(true);                          // Set email format to HTML
     $mail->Subject = 'Register client details and total client details';
     $mail->Body= "$emailTextHtml";    //write the html code
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

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

    
    

你可以做一个测试,如果你需要它通过修补如下代码

# SSH into droplet
# go to project
$ php artisan tinker
$ Mail::send('errors.401', [], function ($message) { $message->to('emmanuelbarturen@gmail.com')->subject('this works!'); });
# check your mailbox