用thinkphp5.1写一个在页面填写邮件表单功能前端用layui写input表单提交
时间: 2024-05-10 08:16:20 浏览: 112
首先,需要在ThinkPHP 5.1中创建一个控制器和视图文件。以下是示例代码:
在控制器中:
```php
namespace app\index\controller;
use think\Controller;
class EmailController extends Controller
{
public function index()
{
return $this->fetch('email');
}
public function send()
{
//获取表单数据
$to = input('post.to');
$subject = input('post.subject');
$content = input('post.content');
//发送邮件
$result = send_email($to, $subject, $content);
if ($result) {
$this->success('发送成功!');
} else {
$this->error('发送失败!');
}
}
}
```
在视图文件中,使用layui的表单组件来创建一个简单的邮件表单:
```html
<div class="layui-form-item">
<label class="layui-form-label">收件人</label>
<div class="layui-input-block">
<input type="text" name="to" placeholder="请输入收件人邮箱" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">主题</label>
<div class="layui-input-block">
<input type="text" name="subject" placeholder="请输入邮件主题" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">内容</label>
<div class="layui-input-block">
<textarea name="content" placeholder="请输入邮件内容" class="layui-textarea"></textarea>
</div>
</div>
```
最后,在控制器中的send方法中,调用send_email函数来发送邮件,示例代码如下:
```php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
function send_email($to, $subject, $content)
{
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'your_email@gmail.com'; // SMTP username
$mail->Password = 'your_password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('your_email@gmail.com', 'Your Name');
$mail->addAddress($to);
$mail->addReplyTo('your_email@gmail.com', 'Your Name');
//Content
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $content;
$mail->send();
return true;
} catch (Exception $e) {
return false;
}
}
```
以上代码仅供参考,实际使用时需要根据自己的情况进行修改。
阅读全文