search
HomeBackend DevelopmentPHP Tutorialphpmailer uses php to send emails case analysis

This time I will bring you a case analysis of phpmailer using php to send emails. What are the precautions for phpmailer to use php to send emails. The following is a practical case, let’s take a look.

Step one:Open the URL to download PHPMailer. PHPMailer requires PHP's sockets extension support, and logging into the QQ mailbox SMTP server must be SSL encrypted, and PHP must also include openssl support.

Step 2: Use the phpinfo() function to view the socket and openssl extension information (wamp server enables this extension by default).

openssl If it is not enabled, please open the php.ini file to enable it

First check whether;extension=php_openssl.dll in php.ini exists. If it exists, remove the preceding comment character ';' , If this line does not exist, add extension=php_openssl.dll.

PHPMailer core file

##Step 3: QQ Email Settings

All mainstream mailboxes support the SMTP protocol, but not all mailboxes are enabled by default. You can manually enable it in the mailbox settings.

After providing the account and password, the third-party service can log in to the SMTP server and use it to control the mail transfer method.

Step 4: Start the SMTP service

Select the IMAP/SMTP service and click to start the service

Step 5:Verify password

Send the text message "Configure email client" to 1069-0700-69

Step 6: Get the authorization code

##SMTP server authentication password, which needs to be kept properly (PS: There are no spaces in the password)

Step 7:

PHP Send EmailBasic Code

The following code demonstrates the use of PHPMailer. Pay attention to the configuration process of the PHPMailer instance.

// 引入PHPMailer的核心文件
require_once("PHPMailer/class.phpmailer.php");
require_once("PHPMailer/class.smtp.php");
 
// 实例化PHPMailer核心类
$mail = new PHPMailer();
// 是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
$mail->SMTPDebug = 1;
// 使用smtp鉴权方式发送邮件
$mail->isSMTP();
// smtp需要鉴权 这个必须是true
$mail->SMTPAuth = true;
// 链接qq域名邮箱的服务器地址
$mail->Host = 'smtp.qq.com';
// 设置使用ssl加密方式登录鉴权
$mail->SMTPSecure = 'ssl';
// 设置ssl连接smtp服务器的远程服务器端口号
$mail->Port = 465;
// 设置发送的邮件的编码
$mail->CharSet = 'UTF-8';
// 设置发件人昵称 显示在收件人邮件的发件人邮箱地址前的发件人姓名
$mail->FromName = '发件人昵称';
// smtp登录的账号 QQ邮箱即可
$mail->Username = '12345678@qq.com';
// smtp登录的密码 使用生成的授权码
$mail->Password = '**********';
// 设置发件人邮箱地址 同登录账号
$mail->From = '12345678@qq.com';
// 邮件正文是否为html编码 注意此处是一个方法
$mail->isHTML(true);
// 设置收件人邮箱地址
$mail->addAddress('87654321@qq.com');
// 添加多个收件人 则多次调用方法即可
$mail->addAddress('87654321@163.com');
// 添加该邮件的主题
$mail->Subject = '邮件主题';
// 添加邮件正文
$mail->Body = '<h1 id="Hello-World">Hello World</h1>';
// 为该邮件添加附件
$mail->addAttachment('./example.pdf');
// 发送邮件 返回状态
$status = $mail->send(); 

I use the code in thinkphp5.0

/**
* 邮件发送
* @param $to 接收人
* @param string $subject 邮件标题
* @param string $content 邮件内容(html模板渲染后的内容)
* @throws Exception
* @throws phpmailerException
*/
function send_email($to,$subject='',$content=''){
  vendor('phpmailer.PHPMailerAutoload');
//require_once 'vendor/phpmailer/PHPMailerAutoload.php';
  $mail = new PHPMailer;
  $arr = db('config')->where('inc_type','smtp')->select();
  $config = convert_arr_kv($arr,'name','value');
  $mail->CharSet = 'UTF-8'; //设定邮件编码,默认ISO-8859-1,如果发中文此项必须设置,否则乱码
  $mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
  $mail->SMTPDebug = 0;
//调试输出格式
//$mail->Debugoutput = 'html';
//smtp服务器
  $mail->Host = $config['smtp_server'];
//端口 - likely to be 25, 465 or 587
  $mail->Port = $config['smtp_port'];
  if($mail->Port === 465) $mail->SMTPSecure = 'ssl';// 使用安全协议
//Whether to use SMTP authentication
  $mail->SMTPAuth = true;
//发送邮箱
  $mail->Username = $config['smtp_user'];
//密码
  $mail->Password = $config['smtp_pwd'];
//Set who the message is to be sent from
  $mail->setFrom($config['smtp_user'],$config['email_id']);
//回复地址
//$mail->addReplyTo('replyto@example.com', 'First Last');
//接收邮件方
  if(is_array($to)){
    foreach ($to as $v){
      $mail->addAddress($v);
    }
  }else{
    $mail->addAddress($to);
  }
  $mail->isHTML(true);// send as HTML
//标题
  $mail->Subject = $subject;
//HTML内容转换
  $mail->msgHTML($content);
//Replace the plain text body with one created manually
//$mail->AltBody = 'This is a plain-text message body';
//添加附件
//$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
  return $mail->send();
}

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed explanation of the use of PHP bubble sort

Detailed explanation of the steps of PHP implementation of binary tree depth and breadth first traversal algorithm

The above is the detailed content of phpmailer uses php to send emails case analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),