密码重置功能:在 Golang 中发送电子邮件
一分耕耘,一分收获!既然都打开这篇《密码重置功能:在 Golang 中发送电子邮件》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!
在撰写本文时,我正在我的应用程序 task-inator 3000 中实现一项为用户重置密码的功能。只是记录我的思考过程和采取的步骤
规划
我正在考虑这样的流程:
- 用户点击“忘记密码?”按钮
- 向请求电子邮件的用户显示模式
- 检查电子邮件是否存在,并将 10 个字符长的 otp 发送到电子邮件
- modal 现在要求输入 otp 和新密码
- 密码已为用户进行哈希处理和更新
关注点分离
前端
- 创建一个模态来输入电子邮件
- 相同的模式然后接受 otp 和新密码
后端
- 创建用于发送电子邮件的 api
- 创建重置密码的api
我将从后端开始
后端
如上所述,我们需要两个 api
1. 发送邮件
api只需要接收用户的邮件,成功后不返回任何内容。因此,创建控制器如下:
// controllers/passwordreset.go func sendpasswordresetemail(c *fiber.ctx) error { type input struct { email string `json:"email"` } var input input err := c.bodyparser(&input) if err != nil { return c.status(fiber.statusbadrequest).json(fiber.map{ "error": "invalid data", }) } // todo: send email with otp to user return c.sendstatus(fiber.statusnocontent) }
现在为其添加一条路线:
// routes/routes.go // password reset api.post("/send-otp", controllers.sendpasswordresetemail)
我将使用 golang 标准库中的 net/smtp。
阅读文档后,我认为最好在项目初始化时创建一个 smtpclient。因此,我会在 /config 目录中创建一个文件 smtpconnection.go。
在此之前,我会将以下环境变量添加到我的 .env 或生产服务器中。
smtp_host="smtp.zoho.in" smtp_port="587" smtp_email="<myemail>" smtp_password="<mypassword>"
我使用的是 zohomail,因此其 smtp 主机和端口(用于 tls)如此处所述。
// config/smtpconnection.go package config import ( "crypto/tls" "fmt" "net/smtp" "os" ) var smtpclient *smtp.client func smtpconnect() { host := os.getenv("smtp_host") port := os.getenv("smtp_port") email := os.getenv("smtp_email") password := os.getenv("smtp_password") smtpauth := smtp.plainauth("", email, password, host) // connect to smtp server client, err := smtp.dial(host + ":" + port) if err != nil { panic(err) } smtpclient = client client = nil // initiate tls handshake if ok, _ := smtpclient.extension("starttls"); ok { config := &tls.config{servername: host} if err = smtpclient.starttls(config); err != nil { panic(err) } } // authenticate err = smtpclient.auth(smtpauth) if err != nil { panic(err) } fmt.println("smtp connected") }
为了抽象,我将在/utils 中创建一个passwordreset.go 文件。该文件目前具有以下功能:
- 生成 otp:生成一个唯一的字母数字 10 位 otp 以在电子邮件中发送
- addotptoredis:以键值格式将 otp 添加到 redis,其中
key -> password-reset:<email> value -> hashed otp expiry -> 10 mins
出于安全原因,我存储 otp 的哈希值而不是 otp 本身
- sendotp:将生成的 otp 发送到用户的电子邮件
在编写代码时,我发现我们需要 5 个常量:
- otp 的 redis 密钥前缀
- otp 过期时间
- 用于 otp 生成的字符集
- 电子邮件模板
- otp 长度
我会立即将它们添加到 /utils/constants.go
// utils/constants.go package utils import "time" const ( authtokenexp = time.minute * 10 refreshtokenexp = time.hour * 24 * 30 // 1 month blacklistkeyprefix = "blacklisted:" otpkeyprefix = "password-reset:" otpexp = time.minute * 10 otpcharset = "abcdefghijklmnopqrstuvwxyz1234567890" emailtemplate = "to: %s\r\n" + "subject: task-inator 3000 password reset\r\n" + "\r\n" + "your otp for password reset is %s\r\n" // public because needed for testing otplength = 10 )
(请注意,我们将从 crypto/rand 导入,而不是 math/rand,因为它将提供真正的随机性)
// utils/passwordreset.go package utils import ( "context" "crypto/rand" "fmt" "math/big" "os" "task-inator3000/config" "golang.org/x/crypto/bcrypt" ) func generateotp() string { result := make([]byte, otplength) charsetlength := big.newint(int64(len(otpcharset))) for i := range result { // generate a secure random number in the range of the charset length num, _ := rand.int(rand.reader, charsetlength) result[i] = otpcharset[num.int64()] } return string(result) } func addotptoredis(otp string, email string, c context.context) error { key := otpkeyprefix + email // hashing the otp data, _ := bcrypt.generatefrompassword([]byte(otp), 10) // storing otp with expiry err := config.redisclient.set(c, key, data, otpexp).err() if err != nil { return err } return nil } func sendotp(otp string, recipient string) error { sender := os.getenv("smtp_email") client := config.smtpclient // setting the sender err := client.mail(sender) if err != nil { return err } // set recipient err = client.rcpt(recipient) if err != nil { return err } // start writing email writecloser, err := client.data() if err != nil { return err } // contents of the email msg := fmt.sprintf(emailtemplate, recipient, otp) // write the email _, err = writecloser.write([]byte(msg)) if err != nil { return err } // close writecloser and send email err = writecloser.close() if err != nil { return err } return nil }
函数generateotp()无需模拟即可测试(单元测试),因此为它编写了一个简单的测试
package utils_test import ( "task-inator3000/utils" "testing" ) func testgenerateotp(t *testing.t) { result := utils.generateotp() if len(result) != utils.otplength { t.errorf("length of otp was not %v. otp: %v", utils.otplength, result) } }
现在我们需要将它们全部放在控制器内。在这之前,我们需要确保数据库中存在提供的电子邮件地址。
控制器的完整代码如下:
func sendpasswordresetemail(c *fiber.ctx) error { type input struct { email string `json:"email"` } var input input err := c.bodyparser(&input) if err != nil { return c.status(fiber.statusbadrequest).json(fiber.map{ "error": "invalid data", }) } // check if user with email exists users := config.db.collection("users") filter := bson.m{"_id": input.email} err = users.findone(c.context(), filter).err() if err != nil { if err == mongo.errnodocuments { return c.status(fiber.statusnotfound).json(fiber.map{ "error": "user with given email not found", }) } return c.status(fiber.statusinternalservererror).json(fiber.map{ "error": "error while finding in the database:\n" + err.error(), }) } // generate otp and add it to redis otp := utils.generateotp() err = utils.addotptoredis(otp, input.email, c.context()) if err != nil { return c.status(fiber.statusinternalservererror).json(fiber.map{ "error": err.error(), }) } // send the otp to user through email err = utils.sendotp(otp, input.email) if err != nil { return c.status(fiber.statusinternalservererror).json(fiber.map{ "error": err.error(), }) } return c.sendstatus(fiber.statusnocontent) }
我们可以通过向正确的 url 发送 post 请求来测试 api。 curl 示例如下:
curl --location 'localhost:3000/api/send-otp' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "yashjaiswal.cse@gmail.com" }'
我们将在本系列的下一部分中创建下一个 api - 用于重置密码
终于介绍完啦!小伙伴们,这篇关于《密码重置功能:在 Golang 中发送电子邮件》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

- 上一篇
- 用户快速重复提交表单,如何防止数据库插入重复数据?

- 下一篇
- 儿童几岁可以练习书法?
-
- Golang · Go教程 | 6小时前 |
- Golang微服务限流熔断技巧
- 482浏览 收藏
-
- Golang · Go教程 | 6小时前 |
- Go语言中如何实现类似C语言的void指针
- 116浏览 收藏
-
- Golang · Go教程 | 6小时前 |
- Golang匿名结构体用法及临时数据场景解析
- 397浏览 收藏
-
- Golang · Go教程 | 6小时前 |
- Golangpanic测试与recover使用技巧
- 435浏览 收藏
-
- Golang · Go教程 | 7小时前 |
- Golang打造简易短链接服务教程
- 309浏览 收藏
-
- Golang · Go教程 | 7小时前 |
- 深入理解Go语言接口:为何无法直接检查接口方法定义及其最佳实践
- 206浏览 收藏
-
- Golang · Go教程 | 7小时前 |
- Golang搭建DNA序列分析工具链教程
- 101浏览 收藏
-
- Golang · Go教程 | 7小时前 |
- 减少Golang反射提升性能的技巧
- 407浏览 收藏
-
- Golang · Go教程 | 7小时前 |
- Golang字符串格式化fmt.Printf全解析
- 140浏览 收藏
-
- Golang · Go教程 | 8小时前 | golang rpc
- GolangRPC多服务调用链管理方法
- 451浏览 收藏
-
- Golang · Go教程 | 8小时前 |
- Golang单例模式实现与使用方法
- 353浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 514次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 499次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- AI Mermaid流程图
- SEO AI Mermaid 流程图工具:基于 Mermaid 语法,AI 辅助,自然语言生成流程图,提升可视化创作效率,适用于开发者、产品经理、教育工作者。
- 722次使用
-
- 搜获客【笔记生成器】
- 搜获客笔记生成器,国内首个聚焦小红书医美垂类的AI文案工具。1500万爆款文案库,行业专属算法,助您高效创作合规、引流的医美笔记,提升运营效率,引爆小红书流量!
- 735次使用
-
- iTerms
- iTerms是一款专业的一站式法律AI工作台,提供AI合同审查、AI合同起草及AI法律问答服务。通过智能问答、深度思考与联网检索,助您高效检索法律法规与司法判例,告别传统模板,实现合同一键起草与在线编辑,大幅提升法律事务处理效率。
- 755次使用
-
- TokenPony
- TokenPony是讯盟科技旗下的AI大模型聚合API平台。通过统一接口接入DeepSeek、Kimi、Qwen等主流模型,支持1024K超长上下文,实现零配置、免部署、极速响应与高性价比的AI应用开发,助力专业用户轻松构建智能服务。
- 820次使用
-
- 迅捷AIPPT
- 迅捷AIPPT是一款高效AI智能PPT生成软件,一键智能生成精美演示文稿。内置海量专业模板、多样风格,支持自定义大纲,助您轻松制作高质量PPT,大幅节省时间。
- 710次使用
-
- Golangmap实践及实现原理解析
- 2022-12-28 505浏览
-
- 试了下Golang实现try catch的方法
- 2022-12-27 502浏览
-
- 如何在go语言中实现高并发的服务器架构
- 2023-08-27 502浏览
-
- go和golang的区别解析:帮你选择合适的编程语言
- 2023-12-29 502浏览
-
- 提升工作效率的Go语言项目开发经验分享
- 2023-11-03 502浏览