Home Backend Development PHP Tutorial PHP implements email subscription mechanism

PHP implements email subscription mechanism

Jun 22, 2023 am 10:40 AM
php mail subscription

In recent years, with the popularity of email and the rapid development of the Internet, many websites have enabled email subscription mechanisms, allowing users to subscribe to updated information on specific content. After receiving emails, users can keep abreast of the latest developments on the website, so The email subscription mechanism has become a very important service.

In website development, PHP has become one of the most popular back-end development languages ​​due to its many advantages such as ease of learning, flexible operation, and low cost. In this article, we will introduce how to use PHP to implement an email subscription mechanism.

1. Design database table

We need to define a user table to store user information. In this article, we set the user table to contain the following fields:

  • id: the user’s unique identifier;
  • email: the user’s email address;
  • created_at : Record the time when the user was created;

The following is the SQL statement to create the user table:

CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
email varchar(255) NOT NULL,
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

2. Write an email Subscription function

After completing the design of the database table, we need to write PHP code to implement the email subscription function. In this article, we will use the PHPMailer library to handle email sending.

First we need to reference the PHPMailer library in the PHP file:

require_once 'path/to/PHPMailer.php';
require_once 'path/to/SMTP.php';

Then, we can use the following code to implement the email subscription function:

$email = $_POST['email']; //Get the email address of the user who submitted the form

//Check whether the email format is correct
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//Query whether the same email address already exists in the database
$stmt = $pdo- >prepare("SELECT COUNT(*) FROM users WHERE email = ?");
$stmt->execute([$email]);
$count = $stmt->fetchColumn();

//If the email address does not exist, insert the user into the database
if ($count == 0) {

$stmt = $pdo->prepare("INSERT INTO users (email) VALUES (?)");
$stmt->execute([$email]);

//发送欢迎邮件
$mail = new PHPMailerPHPMailerPHPMailer();
//SMTP服务器设置
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your-email@gmail.com'; //你的Gmail账号
$mail->Password = 'your-password'; //你的Gmail密码
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;

//邮件设置
$mail->setFrom('your-email@gmail.com', 'Your Name');
$mail->addAddress($email);
$mail->Subject = 'Welcome to our website!';
$mail->Body = 'Thank you for subscribing to our mailing list!';

//发送邮件
$mail->send();

//返回订阅成功的提示信息
echo json_encode(['success' => true, 'message' => 'Subscription successful!']);
Copy after login

} else {

//返回邮箱已存在的提示信息
echo json_encode(['success' => false, 'message' => 'Email address already exists!']);
Copy after login

}
} else {
//Return the error message that the email format is incorrect
echo json_encode(['success' => false, 'message' => 'Invalid email address!']) ;
}
?>

In the above code, we first obtain the email address of the user who submitted the form, and then use the filter_var function to check whether the email format is correct. If the email address is correct, query whether the same email address already exists in the database. If it does not exist, insert the user into the database, and then send a welcome email. After the sending is completed, a prompt message indicating successful subscription will be returned; if the email address already exists, If the mailbox format is incorrect, the mailbox format is incorrect. If the mailbox format is incorrect, the mailbox format is incorrect.

3. Write an email unsubscription function

The email subscription mechanism generally also includes an email unsubscription function, and users can unsubscribe at any time. We can use the following code to implement the email unsubscription function:

$email = $_POST['email']; //Get the email address of the user who submitted the form

//Check whether the email format is correct
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//Query whether the same email address exists in the database
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
$stmt->execute([$email]);
$count = $stmt->fetchColumn();

//If the email address exists, delete the user from the database
if ($count == 1) {

$stmt = $pdo->prepare("DELETE FROM users WHERE email = ?");
$stmt->execute([$email]);

//返回退订成功的提示信息
echo json_encode(['success' => true, 'message' => 'Unsubscription successful!']);
Copy after login

} else {

//返回邮箱不存在的提示信息
echo json_encode(['success' => false, 'message' => 'Email address does not exist!']);
Copy after login

}
} else {
//Return the error message that the email format is incorrect
echo json_encode(['success' => false, 'message' => 'Invalid email address!']);
}
?>

In the above code, we first obtain the user's email address submitted by the form, and then use the filter_var function to check whether the email format is correct. If the email address is correct, query whether the same email address exists in the database. If it exists, delete the user from the database and return a successful unsubscription message; if the email address does not exist, return "Email does not exist". Error message; if the email format is incorrect, an error message of "The email format is incorrect" will be returned.

4. Conclusion

Through the introduction of this article, we can use PHP to implement the email subscription mechanism, including two functions: subscription and unsubscription. Through these functions, users can keep abreast of the latest developments on the website and can choose whether to receive updated information, which plays a very important role in the user experience and marketing effectiveness of the website.

The above is the detailed content of PHP implements email subscription mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles