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

我安装了WampServer。

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


当前回答

这可以使用PHP的mail()函数实现。记住,邮件功能将不能在本地服务器上工作。

<?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);
?>

参考:

邮件

其他回答

对于大多数项目,我现在使用Swift mailer。这是一种非常灵活和优雅的面向对象的发送电子邮件的方法,它是由给我们提供流行的Symfony框架和Twig模板引擎的同一个人创建的。


基本用法:

require 'mail/swift_required.php';

$message = Swift_Message::newInstance()
    // The subject of your email
    ->setSubject('Jane Doe sends you a message')
    // The from address(es)
    ->setFrom(array('jane.doe@gmail.com' => 'Jane Doe'))
    // The to address(es)
    ->setTo(array('frank.stevens@gmail.com' => 'Frank Stevens'))
    // Here, you put the content of your email
    ->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');

if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
    echo json_encode([
        "status" => "OK",
        "message" => 'Your message has been sent!'
    ], JSON_PRETTY_PRINT);
} else {
    echo json_encode([
        "status" => "error",
        "message" => 'Oops! Something went wrong!'
    ], JSON_PRETTY_PRINT);
}

有关如何使用Swift mailer的更多信息,请参阅官方文档。

如果你对html格式的电子邮件感兴趣,请确保传递Content-type: text/html;在头文件中。例子:

// multiple recipients
$to  = 'aidan@example.com' . ', '; // note the comma
$to .= 'wez@example.com';

// subject
$subject = 'Birthday Reminders for August';

// message
$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';

// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);

要了解更多细节,请查看php邮件函数。

试试这个:

<?php
$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";

mail($to,$subject,$txt,$headers);
?>

还可以查看PEAR邮件包PEAR mail Page

它似乎比内置的标准mail()函数健壮一些(如果标准函数不够的话)。

下面是该页面的一段摘录,展示如何使用它。PEAR邮件发送()用法

<?php
    include('Mail.php');

    $recipients = 'joe@example.com';

    $headers['From']    = 'richard@example.com';
    $headers['To']      = 'joe@example.com';
    $headers['Subject'] = 'Test message';

    $body = 'Test message';

    $smtpinfo["host"] = "smtp.server.com";
    $smtpinfo["port"] = "25";
    $smtpinfo["auth"] = true;
    $smtpinfo["username"] = "smtp_user";
    $smtpinfo["password"] = "smtp_password";


    // Create the mail object using the Mail::factory method
    $mail_object =& Mail::factory("smtp", $smtpinfo); 

    $mail_object->send($recipients, $headers, $body);
?> 

使用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/