基于flask手把手教你做个可以把简历发到邮箱里的官网(干货)
一、具体功能和依赖
- 展示首页、关于我们、联系方式和加入我们页面
- 表单提交后自动发送邮件通知
- 简历投递功能
- 表单验证
- 邮件发送功能
在这里,我们需要用到flask,flask_wtf,flask_mail
指令如下:
pip3 install flask flask-wft flask-mail
二、界面和路由配置(可直接复制)
网页编写(可直接复制)
下面是index.html的示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="{{ url_for('static',filename='img/logo.jpg') }}">
<link rel="stylesheet" href="{{ url_for('static',filename ='css/base.css') }}">
<title>首页</title>
</head>
<body>
<section>
首页
</section>
<footer>
<p>我的网页 ©</p>
</footer>
</body>
</html>
其中引用了static文件夹下的base.css,这是全局样式入口,可以在里面编写全局样式。
其中:url_for 是 Flask 框架中 Jinja2 模板引擎提供的一个核心函数,配合[{}}语法,用于动态生成 URL。它通过视图函数名或端点(endpoint)反向解析出对应的 URL,避免硬编码路径,提高代码的可维护性和灵活性
你学会了喵
所以文件目录大概是这样,可以在这个基础上自行增加
guanwang/
├── static/ # 静态文件存放目录
│ ├── css/
│ │ └──base.css
│ └── img/ # 存放图片,模版中用到了logo.jpg
├── templates/ # 网页模版
│ └── index.html
└── app.py # 主文件
接着,可以在templates/下面继续添加两个界面
about.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="{{ url_for('static',filename='img/logo.jpg') }}">
<link rel="stylesheet" href="{{ url_for('static',filename ='css/base.css') }}">
<title>关于</title>
</head>
<body>
<section>
关于
</section>
<footer>
<p>我的网页 ©</p>
</footer>
</body>
</html>
contact.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="{{ url_for('static',filename='img/logo.jpg') }}">
<link rel="stylesheet" href="{{ url_for('static',filename ='css/base.css') }}">
<title>联系我们</title>
<style>
/* 错误提示样式(不破坏原有CSS) */
.error {
color: #dc3545; /* 红色错误提示 */
font-size: 0.9rem;
margin-top: 0.3rem;
margin-bottom: 0;
}
/* 保持输入框焦点样式 */
input:focus, textarea:focus {
outline: 2px solid #f7c08a;
border-color: #f7c08afa;
}
</style>
</head>
<body>
<section id="contact-form" class="py">
<div class="container">
<p>请填写信息联系我们</p>
<form method="POST" action="/contact">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="name">称呼</label>
<!-- 保留已填内容 + 绑定name属性 -->
<input type="text" name="name" id="name" value="{{ name if name else '' }}">
<!-- 错误提示 -->
{% if errors and errors.name %}
<p class="error">{{ errors.name }}</p>
{% endif %}
</div>
<div class="form-group">
<label for="phone">电话</label>
<input type="text" name="phone" id="phone" value="{{ phone if phone else '' }}">
{% if errors and errors.phone %}
<p class="error">{{ errors.phone }}</p>
{% endif %}
</div>
<div class="form-group">
<label for="contact">邮箱或其他联系方式</label>
<input type="text" name="contact" id="contact" value="{{ contact if contact else '' }}">
{% if errors and errors.contact %}
<p class="error">{{ errors.contact }}</p>
{% endif %}
</div>
<div class="form-group">
<label for="message">您的简历</label>
<textarea name="message" id="message" rows="5">{{ message if message else '' }}</textarea>
{% if errors and errors.message %}
<p class="error">{{ errors.message }}</p>
{% endif %}
</div>
<button type="submit" class="btn">提交</button>
</form>
</div>
</section>
<footer id="main-footer">
<p>黑鸟惊雷科技 ©</p>
</footer>
</body>
</html>
可以看到,这上面用jinja2模版引擎写了个表单,用于提交信息,如果后端校验不通过,就返回error对象,根据模版中的条件判断语句渲染,加上css样式突出字体
三、路由配置
flask提供了装饰器来配置路由:(在app.py中编写)
这是首页:
@app.route('/')
def index():
return render_template('index.html')
这是关于我们:
#关于我们
@app.route('/about')
def about():
return render_template('about.html')
而提交简历表单使用post方法,直接浏览网页便是get方法:
加上后端的表单校验如下,并且提交到邮箱:
先是基础配置:
from flask import Flask,request,render_template,redirect,url_for
from flask_mail import Mail, Message
app = Flask(__name__)
# ====================== 邮箱配置(核心)======================
# 1. 邮件服务器地址:163 邮箱的 SMTP 服务器固定为 smtp.163.com
app.config['MAIL_SERVER'] = 'smtp.163.com'
# 2. 邮件服务器端口:SSL 加密方式对应端口 465(必填,不能改)
app.config['MAIL_PORT'] = 465
# 3. 启用 SSL 加密:163 邮箱要求必须用 SSL,否则无法连接
app.config['MAIL_USE_SSL'] = True
# 4. 发送方邮箱账号:你的 163 邮箱(比如 xxx@163.com)
# 注意:必须和下面的授权码对应,不能填错
app.config['MAIL_USERNAME'] = '' # 例:15939344511@163.com
# 5. 发送方邮箱授权码:不是邮箱登录密码!是邮箱专门用于第三方工具(如 Flask)的授权码
app.config['MAIL_PASSWORD'] = '' # 去邮箱官网开启此功能并获得授权码
# 6. 可选:关闭邮件发送时的调试信息(生产环境建议开启)
app.config['MAIL_DEBUG'] = False
# 初始化邮件对象:把 Flask 应用和邮件配置绑定
mail = Mail(app)
这里用网易邮箱为例子,需要开启 SMTP 功能,并生成授权码
下面是后端处理提交信息并且发给邮箱的例子
#联系我们
import re
@app.route('/contact',methods=['POST','GET'])
def contact():
if request.method == 'POST':
# 1. 接收表单数据(去除首尾空格)
name = request.form.get('name', '').strip()
phone = request.form.get('phone', '').strip()
contact = request.form.get('contact', '').strip() # 邮箱或其他联系方式
message = request.form.get('message', '').strip()
# 2. 初始化错误字典(存储验证失败信息)
errors = {}
# 3. 表单验证规则
# 验证称呼(必填)
if not name:
errors['name'] = '称呼不能为空'
# 验证电话(必填 + 11位手机号格式)
if not phone:
errors['phone'] = '电话不能为空'
elif not re.match(r'^1[3-9]\d{9}$', phone):
errors['phone'] = '手机号格式不正确(需11位有效号码)'
# 验证联系方式(必填 + 邮箱格式或允许其他内容)
if not contact:
errors['contact'] = '邮箱或联系方式不能为空'
# 可选:如果是邮箱,验证格式(不强制,因为允许其他联系方式)
elif '@' in contact and not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', contact):
errors['contact'] = '如果填写邮箱,请输入正确格式(例:xxx@xxx.com)'
# 验证需求(必填 + 最少10字)
if not message:
errors['message'] = '您的需求不能为空'
elif len(message) < 10:
errors['message'] = '需求描述请至少填写10个字'
# 4. 处理验证结果
if errors:
# 验证失败:返回表单页,携带错误信息和已填内容
return render_template('contact.html', errors=errors,
name=name, phone=phone, contact=contact, message=message)
else:
# 验证成功:执行后续操作,发送邮件通知
try:
# 创建邮件对象
msg = Message(
subject=f"【新联系请求】来自 {name}", # 邮件标题(一目了然)
sender=app.config['MAIL_USERNAME'], # 发送方:你的 163 邮箱
recipients=[app.config['MAIL_USERNAME']], # 接收方:也是你的 163 邮箱(表单提交后发给自己)
# 邮件正文内容(用 f-string 把表单数据拼接进去)
body=f"""
🌟 收到新的客户联系请求 🌟
==================================
称呼:{name}
电话:{phone}
联系方式(邮箱/微信等):{contact}
需求描述:{message}
==================================
请及时回复客户!
"""
)
mail.send(msg)
print("邮件发送成功")
except Exception as e:
# 捕获邮件发送失败的错误(比如授权码错、网络问题)
print(f"邮件发送失败:{str(e)}") # 控制台打印错误,方便排查
# 可选:给用户显示发送失败提示(不影响表单提交)
errors['email_error'] = '表单提交成功,但通知邮件发送失败,请手动查看后台记录'
return render_template('contact.html', errors=errors, name=name, phone=phone, contact=contact, message=message)
# 跳转到感谢页,避免表单重复提交),使用redirect重定向
return redirect(url_for('thankyou'))
else:
return render_template('contact.html')
可能有点复杂,但是我都做了比较详细的注释,希望你看得懂喵
当然,可以在html中使用超链接跳转到别的页面
比如:
<a href="/about">关于我们</a>
<a href="/contact">联系我们</a>
你学会了喵
四、接下来的方向
接下来可以做更多界面
或者加点有趣的功能
也可以做防止夸站点请求(csrf)伪造的脚本
如果项目要部署上线,简易用gunicorn,这是专门的Python WSGI HTTP 服务器,用于运行 Python Web 应用
封面是个我自己随手做的例子,用了一张背景图和一个按钮,设计供参考
1865

被折叠的 条评论
为什么被折叠?



