Backend Development 7 min read

Implementing Email Sending with PHPMailer in ThinkPHP (Backend and Frontend Integration)

This tutorial explains how to configure PHPMailer in a ThinkPHP project, set up SMTP credentials, create a reusable sendMail function, generate verification codes, and integrate a frontend form with AJAX to send password‑reset emails securely.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Implementing Email Sending with PHPMailer in ThinkPHP (Backend and Frontend Integration)

The article provides a step‑by‑step guide for sending emails using PHPMailer within a ThinkPHP application, covering both backend configuration and frontend interaction.

Preparation

1. Download the PHPMailer library and place it in Application/Thinkphp/Library/Vendor/ . 2. Enable SMTP in the configuration, using an example of a NetEase email account.

Configuration (config.php)

<code>// 配置邮件发送服务器
'MAIL_HOST' => 'smtp.163.com', // smtp服务器的名称
'MAIL_SMTPAUTH' => TRUE, // 启用smtp认证
'MAIL_USERNAME' => '[email protected]', // 你的邮箱名
'MAIL_FROM' => '[email protected]', // 发件人地址
'MAIL_FROMNAME' => '南京商丘商会', // 发件人姓名
'MAIL_PASSWORD' => 'a3392894', // 邮箱密码
'MAIL_CHARSET' => 'utf-8', // 设置邮件编码
'MAIL_ISHTML' => TRUE, // 是否HTML格式邮件</code>

Mail Sending Function (function.php)

<code>&lt;?php
/**
 * 邮件发送函数
 */
function sendMail($to, $title, $content) {
    Vendor('PHPMailer.PHPMailerAutoload');
    $mail = new PHPMailer(); // 实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host = C('MAIL_HOST'); // smtp服务器的名称(这里以QQ邮箱为例)
    $mail->SMTPAuth = C('MAIL_SMTPAUTH'); // 启用smtp认证
    $mail->Username = C('MAIL_USERNAME'); // 你的邮箱名
    $mail->Password = C('MAIL_PASSWORD'); // 邮箱密码
    $mail->From = C('MAIL_FROM'); // 发件人地址(也就是你的邮箱地址)
    $mail->FromName = C('MAIL_FROMNAME'); // 发件人姓名
    $mail->AddAddress($to, "尊敬的客户");
    $mail->WordWrap = 50; // 设置每行字符长度
    $mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
    $mail->CharSet = C('MAIL_CHARSET'); // 设置邮件编码
    $mail->Subject = $title; // 邮件主题
    $mail->Body = $content; // 邮件内容
    $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; // 邮件正文不支持HTML的备用显示
    if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "Message sent!";
    }
}
</code>

Backend Logic

<code>public function createSMSCode($length = 6) {
    $min = pow(10, ($length - 1));
    $max = pow(10, $length) - 1;
    return rand($min, $max);
}

// ajax发送邮件
public function e_mail_send() {
    $e_mail = I("post.e_mail");
    $result = M("user")->where(array("e_mail" => $e_mail))->find();
    if ($result) {
        $code = $this->createSMSCode();
        session("code", $code);
        session("e_mail", $e_mail);
        SendMail($e_mail, "南京商丘商会验证码", "您的验证码是" . $code . ",请正确填写");
        $data = "yes";
    } else {
        $data = "no";
    }
    $this->ajaxReturn($data);
}
</code>

Frontend Form (HTML)

<code>&lt;p class="fot_main"&gt;
    &lt;p class="container"&gt;
        &lt;p class="row"&gt;
            &lt;p class="my_ar"&gt;
                &lt;h3&gt;密码找回!&lt;br/&gt;&lt;span&gt;请填入您的邮箱进行密码找回&lt;/span&gt;&lt;br/&gt;&lt;span&gt;发送后请注意查收邮箱信息填入验证码中&lt;/span&gt;&lt;/h3&gt;
                &lt;form method="post" action="{:U('Forget/forget_do')}"&gt;
                    &lt;label&gt;请输入注册邮箱:&lt;/label&gt;
                    &lt;input type="text" name="e_mail" id="e_mail" class="fot_name"&gt;
                    &lt;a href="javascript:;" id="send" class="fasong" style="display:inline-block;width:70px;height:29px;background:#f3980f;color:#fff;line-height:29px;text-align:center;border:1px solid #919191;"&gt;发送&lt;/a&gt;&lt;br/&gt;
                    &lt;p style="margin-left:130px;color:orange;" id="back"&gt;&lt;/p&gt;
                    &lt;label&gt;验证码:&lt;/label&gt;
                    &lt;input type="text" name="code" class="yan"/&gt;&lt;br/&gt;
                    &lt;label&gt;新密码:&lt;/label&gt;
                    &lt;input type="text" name="npwd" class="xin_password"/&gt;&lt;br/&gt;
                    &lt;label&gt;确认密码:&lt;/label&gt;
                    &lt;input type="text" name="renpwd" class="xin_password"/&gt;&lt;br/&gt;
                    &lt;p class="ccc"&gt;&lt;input type="submit" value="提交" class="sub"&gt;&lt;/p&gt;
                &lt;/form&gt;
            &lt;/p&gt;
        &lt;/p&gt;
    &lt;/p&gt;
&lt;/p&gt;
</code>

AJAX Script

<code>&lt;script&gt;
    $("#send").click(function(){
        var e_mail = $("#e_mail").val();
        $.post("{:U('Forget/e_mail_send')}", "e_mail=" + e_mail, function(data){
            if(data == "yes"){
                $("#back").html("发送成功,请查收邮件");
            } else {
                $("#back").html("邮箱错误或不存在");
            }
        });
    });
&lt;/script&gt;
</code>

The article concludes with screenshots of the final page and a link to view the original article for further details.

frontendAJAXEmailThinkPHPPHPMailer
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.