golang邮箱发送验证码

常用邮箱:
QQ 邮箱
POP3 服务器地址:qq.com(端口:995)
SMTP 服务器地址:smtp.qq.com(端口:465/587)

163 邮箱:
POP3 服务器地址:pop.163.com(端口:110)
SMTP 服务器地址:smtp.163.com(端口:25)

126 邮箱:
POP3 服务器地址:pop.126.com(端口:110)
SMTP 服务器地址:smtp.126.com(端口:25)
代码如下:
首先导入包:

"net/smtp"
"math/rand"//随机数
"time"
"fmt"
"log"

定义一个Map存放邮箱号及对应随机码

var Code = make(map[string]int) //key为Email,value为随机码

邮箱发送验证码

func SendEmail(email string) int {
     //smtp.PlainAuth()
     // 参数1:Usually identity should be the empty string, to act as username
     // 参数2:username
    //参数3:password
    //参数4:host
	auth := smtp.PlainAuth("", "[email protected]", "此处填写邮箱密码", "smtp.163.com")
	to := []string{"[email protected]"}
	//发送随机数为验证码
	// Seed uses the provided seed value to initialize the default Source to a
	// deterministic state. If Seed is not called, the generator behaves as
	// if seeded by Seed(1). Seed values that have the same remainder when
	// divided by 2^31-1 generate the same pseudo-random sequence.
	// Seed, unlike the Rand.Seed method, is safe for concurrent use.
	rand.Seed(time.Now().Unix())
	// Intn returns, as an int, a non-negative pseudo-random number in [0,n)
	num := rand.Intn(10000)
	//发送内容使用base64 编码,单行不超过80字节,需要插入\r\n进行换行
	//The msg headers should usually include
	// fields such as "From", "To", "Subject", and "Cc".  Sending "Bcc"
	// messages is accomplished by including an email address in the to
	// parameter but not including it in the msg headers.
	str := fmt.Sprintf("From:[email protected]\r\nTo:[email protected]\r\nSubject:verifycode\r\n\r\n,%d,\r\n.", num)//邮件格式
	msg := []byte(str)
	err := smtp.SendMail("smtp.163.com:25", auth, "[email protected]", to, msg)
	if err != nil {
		log.Fatal(err)
	}
	return num
}
发布了34 篇原创文章 · 获赞 12 · 访问量 6962

猜你喜欢

转载自blog.csdn.net/weixin_45604257/article/details/102963591