如何获取帐户激活电子邮件以发送PHP?

如何解决如何获取帐户激活电子邮件以发送PHP?

我正在使用PHP和MYSQL创建注册和登录系统。当用户首次使用其用户名,电子邮件和密码进行注册时,他们应该会收到一封带有激活链接的电子邮件。但是,尽管帐户详细信息已成功进入数据库,但未发送帐户激活电子邮件。

这是我的config.php

<?php
// database hostname
define('db_host','localhost');
// database username
define('db_user','username');
// database password
define('db_pass','password');
// database name
define('db_name','dbname');
// database charset
define('db_charset','utf8');
// Email activation variables
// account activation required?
define('account_activation',true);
define('mail_from','StanCafe <noreply@stancafe.com>');
// Link to activation file,update this
define('activation_link','https://stancafe.com/StanCafe/activate.php');
?>

这是我的main.php

<?php
// The main file contains the database connection,session initializing,and functions,other PHP files will depend on this file.
// Include thee configuration file
include_once 'config.php';
// We need to use sessions,so you should always start sessions using the below code.
session_start();
// No need to edit below
try {
    $pdo = new PDO('mysql:host=' . db_host . ';dbname=' . db_name . ';charset=' . db_charset,db_user,db_pass);
} catch (PDOException $exception) {
    // If there is an error with the connection,stop the script and display the error.
    exit('Failed to connect to database!');
}
// The below function will check if the user is logged-in and also check the remember me cookie
function check_loggedin($pdo,$redirect_file = 'index.php') {
    // Check for remember me cookie variable and loggedin session variable
    if (isset($_COOKIE['rememberme']) && !empty($_COOKIE['rememberme']) && !isset($_SESSION['loggedin'])) {
        // If the remember me cookie matches one in the database then we can update the session variables.
        $stmt = $pdo->prepare('SELECT * FROM accounts WHERE rememberme = ?');
        $stmt->execute([ $_COOKIE['rememberme'] ]);
        $account = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($account) {
            // Found a match,update the session variables and keep the user logged-in
            session_regenerate_id();
            $_SESSION['loggedin'] = TRUE;
            $_SESSION['name'] = $account['username'];
            $_SESSION['id'] = $account['id'];
            $_SESSION['role'] = $account['role'];
        } else {
            // If the user is not remembered redirect to the login page.
            header('Location: ' . $redirect_file);
            exit;
        }
    } else if (!isset($_SESSION['loggedin'])) {
        // If the user is not logged in redirect to the login page.
        header('Location: ' . $redirect_file);
        exit;
    }
}
// Send activation email function
function send_activation_email($email,$code) {
    $subject = 'Account Activation Required';
    $headers = 'From: ' . mail_from . "\r\n" . 'Reply-To: ' . mail_from . "\r\n" . 'Return-Path: ' . mail_from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n";
    $activate_link = activation_link . '?email=' . $email . '&code=' . $code;
    $email_template = str_replace('%link%',$activate_link,file_get_contents('https://stancafe.com/StanCafe/activation-email-template.html'));
    mail($email,$subject,$email_template,$headers,'-f ' . mail_from);
}
?>

这是我的Activation-email-template.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

  <head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Account Activation Required</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">

    <style>

      .heading {
        font-family: 'Montserrat',sans-serif;
        text-align: center;
        font-weight: bold;
        color: white;
        font-size: 2rem;
}

      .footer {
        font-family: "Montserrat",sans-serif;
        font-weight: lighter;
        color: white;
        font-size: 0.8rem;
}

      a {
        text-decoration: none;
}

    </style>


  </head>

  <body style="margin: 0; padding: 0;">

   <table border="0" cellpadding="0" cellspacing="0" width="100%">
    <tr>
     <td  style="padding: 20px 0 30px 0;">

       <table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse; border: 1px solid #CCCCCC;">
        <tr>
         <td bgcolor="#1DA0F2" style="padding: 40px 0 30px 0;" class="heading">
          Welcome to StanCafe!
         </td>
        </tr>
        <tr>
         <td bgcolor="#FFFFFF" style="padding: 40px 30px 40px 30px;">
           <table border="0" cellpadding="0" cellspacing="0" width="100%">
             <tr>
              <td style="padding: 20px 0 30px 0; text-align: center;">
               <img src="https://img.icons8.com/doodle/100/000000/party-whistle.png" alt="fireworks">
              </td>
             </tr>
             <tr>
              <td style="padding: 20px 0 30px 0; text-align: center; font-family: Montserrat,sans-serif;">
               Thank you for joining StanCafe! We're sure that you'll find some great communities. Before we get started,we'll need you to verify your email.
              </td>
             </tr>
             <tr>
              <td style="padding: 20px 0 30px 0; text-align: center; font-family: Montserrat,sans-serif;">
                <a href="%link%">Click here to activate your account.</a>
              </td>
             </tr>
            </table>
           </td>
          </tr>
          <tr>
           <td bgcolor="#1DA0F2" style="padding: 40px 0 30px 0; text-align: center;" class="footer">
            Sent by StanCafe.<br>Images courtesy of <a href="https://icons8.com/icon/81256/party-whistle">Party Whistle icon by Icons8</a>
           </td>
          </tr>
          <tr>
         </table>

     </td>
    </tr>
   </table>

  </body>


</html>

这是我的register.php

<?php
include 'main.php';
// Now we check if the data was submitted,isset() function will check if the data exists.
if (!isset($_POST['username'],$_POST['password'],$_POST['cpassword'],$_POST['email'])) {
    // Could not get the data that should have been sent.
    exit('Please complete the registration form!');
}
// Make sure the submitted registration values are not empty.
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email'])) {
    // One or more values are empty.
    exit('Please complete the registration form');
}
// Check to see if the email is valid.
if (!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
    exit('Email is not valid!');
}
// Username must contain only characters and numbers.
if (!preg_match('/^[a-zA-Z0-9]+$/',$_POST['username'])) {
    exit('Username is not valid!');
}
// Password must be between 5 and 20 characters long.
if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) {
    exit('Password must be between 5 and 20 characters long!');
}
// Check if both the password and confirm password fields match
if ($_POST['cpassword'] != $_POST['password']) {
    exit('Passwords do not match!');
}
// Check if the account with that username already exists
$stmt = $pdo->prepare('SELECT id,password FROM accounts WHERE username = ? OR email = ?');
$stmt->execute([ $_POST['username'],$_POST['email'] ]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
// Store the result so we can check if the account exists in the database.
if ($account) {
    // Username already exists
    echo 'Username and/or email exists!';
} else {
    // Username doesnt exists,insert new account
    $stmt = $pdo->prepare('INSERT INTO accounts (username,password,email,activation_code) VALUES (?,?,?)');
    // We do not want to expose passwords in our database,so hash the password and use password_verify when a user logs in.
    $password = password_hash($_POST['password'],PASSWORD_DEFAULT);
    $uniqid = account_activation ? uniqid() : '';
    $stmt->execute([ $_POST['username'],$password,$_POST['email'],$uniqid ]);
    if (account_activation) {
        // Account activation required,send the user the activation email with the "send_activation_email" function from the "main.php" file
        send_activation_email($_POST['email'],$uniqid);
        echo 'Please check your email to activate your account!';
    } else {
        echo 'You have successfully registered,you can now login!';
    }
}
?>

当我在注册页面上按“注册”时,它显示“请检查您的电子邮件以激活您的帐户!”但没有发送电子邮件。

我尝试编辑电子邮件的html并使用绝对链接,但是没有任何效果。

非常感谢您的帮助!

谢谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res