HotGO基于go-simple-mail实现邮件发送

HotGO基于go-simple-mail实现邮件发送

 次点击
15 分钟阅读

前言

HotGo框架中默认是使用net/smtp库来实现邮件发送的,但是我这里测试的是没办法发送邮件的,调用smtp.SendMail后会卡在smtp.Dial里长时间连接不到SMTP服务器,然后就会报EOF错误,所以我在原邮件发送的逻辑上把net/smtp替换成了go-simple-mail,测试功能一切正常。

代码变动的地方为internal -> library -> ems - ems.go中的sendToMail函数

SMTP 相关配置在HotGo框架后台 -> 系统设置 -> 配置管理 -> 邮件设置中进行设置

依赖安装

go get github.com/xhit/go-simple-mail/v2

HotGo框架

https://gitee.com/bufanyun/hotgo

日志美化

http://blog.hc8.ren/archives/1730536195742

修改前

func sendToMail(config *model.EmailConfig, to, subject, body, mailType string) error {
	if config == nil {
		return gerror.New("邮件配置不能为空")
	}

	var (
		contentType string
		auth        = smtp.PlainAuth("", config.User, config.Password, config.Host)
		sendTo      = strings.Split(to, ";")
	)

	if len(sendTo) == 0 {
		return gerror.New("收件人不能为空")
	}

	for _, em := range sendTo {
		if !validate.IsEmail(em) {
			return gerror.Newf("邮件格式不正确,请检查:%v", em)
		}
	}

	if mailType == "html" {
		contentType = "Content-Type: text/" + mailType + "; charset=UTF-8"
	} else {
		contentType = "Content-Type: text/plain" + "; charset=UTF-8"
	}

	msg := []byte("To: " + to + "\r\nFrom: " + config.SendName + "<" + config.User + ">" + "\r\nSubject: " + subject + "\r\n" + contentType + "\r\n\r\n" + body)
	return smtp.SendMail(config.Addr, auth, config.User, sendTo, msg)
}

修改后

func sendToMail(config *model.EmailConfig, to, subject, body, mailType string) error {
	if config == nil {
		return gerror.New("邮件配置不能为空")
	}
	// 创建 SMTP 服务器配置
	smtpServer := mail.NewSMTPClient()
	smtpServer.Host = config.Host              // SMTP 服务器地址
	smtpServer.Port = int(config.Port)         // SMTP 端口
	smtpServer.Username = config.User          // 邮箱地址
	smtpServer.Password = config.Password      // 邮箱密码
	smtpServer.Encryption = mail.EncryptionSSL // 使用 TLS 加密
	smtpServer.KeepAlive = true                // 不保持连接
	smtpServer.ConnectTimeout = 10 * time.Second
	smtpServer.SendTimeout = 10 * time.Second
	var (
		//contentType string
		sendTo = strings.Split(to, ";")
	)
	if len(sendTo) == 0 {
		return gerror.New("收件人不能为空")
	}

	// 连接 SMTP 服务器
	smtpClient, err := smtpServer.Connect()
	if err != nil {
		g.Log().Errorf(gctx.New(), "Failed to connect to SMTP server: %v", err.Error())
		return fmt.Errorf("邮件发送失败")
	}
	defer func() {
		if smtpClient != nil {
			smtpClient.Close()
			log.Println("SMTP connection closed.")
		}
	}()

	// 邮箱地址使用;进行分隔以实现批量发送
	for _, em := range sendTo {
		if !validate.IsEmail(em) {
			return gerror.Newf("邮件格式不正确,请检查:%v", em)
		}

		// 创建邮件
		email := mail.NewMSG()
		email.SetFrom(fmt.Sprintf("%s <%s>", config.SendName, config.User)).
			AddTo(em).
			SetSubject(subject)

		if mailType == "html" {
			//contentType = "Content-Type: text/" + mailType + "; charset=UTF-8"
			email.SetBody(mail.TextHTML, body)
		} else {
			//contentType = "Content-Type: text/plain" + "; charset=UTF-8"
			email.SetBody(mail.TextPlain, body)
		}
		// 发送邮件
		err = email.Send(smtpClient)
		if err != nil {
			g.Log().Errorf(gctx.New(), "邮件发送失败: %v", err.Error())
			return err
		}
	}
	return err
}

© 本文著作权归作者所有,未经许可不得转载使用。