go写email邮件发送html

用的是 gopkg.in/gomail.v2

go写email邮件发送html_第1张图片

// sent.go
package service

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"gopkg.in/gomail.v2"
	"strings"
)
type CmsSentService struct {}

// 发送邮件
func (s *CmsSentService) SentEmail(content string, subject string, addressHeader string, config g.Map) {

	// 邮件开启
	if gconv.Int(config["remindEmail"]) == 1 {
		// 设置 SMTP 服务器的认证信息
		smtp := gconv.String(config["smtp"])
		smtpPort := 465
		senderEmail := gconv.String(config["sendEmail"])
		senderPassword := gconv.String(config["pass"])

		body := content
		// 邮件内容
		toEmail := gconv.String(config["requestEmail"])
		toEmails := strings.Split(toEmail, "|")

		m := gomail.NewMessage()
		m.SetHeader("To", toEmails...)
		m.SetHeader("Subject", subject)
		m.SetAddressHeader("From", senderEmail, addressHeader)
		m.SetBody("text/html", body)

		d := gomail.NewDialer(smtp, smtpPort, senderEmail, senderPassword)
		// 发送
		err := d.DialAndSend(m)
		if err != nil {
			panic(err)
		}
		g.Log().Debug(ctx, "邮件发送成功")
		fmt.Println("发送成功")
	}

}

调用方法发送email
content如果是是html,那么 m.SetBody(“text/html”, body),就必须写text/html,如果是单文本,就是text/plain

func main() {
	orderContent := "订单到期"
	domainContent := "域名到期"
	content := fmt.Sprintf("

以下编号即将到期:

%s,

以下域名即将到期

%s"
, orderContent, domainContent) subject := "有新的留言" addressHeader := "通知邮件" config := g.Map{ "remindEmail":1, "smtp": "smtp.qq.com", "sendEmail":"", "pass":"", "requestEmail":"", } service.SentEmail(content, subject, addressHeader, config) }

你可能感兴趣的:(go,golang,email,后端)