golong实现邮件发送

1. 发送邮件包

package myMail

import (
	"crypto/tls"
	"fmt"
	"github.com/go-admin-team/go-admin-core/sdk/config"
	ext "go-admin/config"
	"net/smtp"
	"strings"
	"time"
)

type MyEmail struct{
	Host string
	Port string
	AuthUser string
	AuthPass string
}

func (e *MyEmail)SendEmail(mailTo string, subject string, body string) (bool, error) {
    //这里是从配置文件读邮件服务器配置信息
	cfg, _ := config.ExtendConfig.(*ext.Extend)
	emailCfg := cfg.Emailcfg
	//没有配置文件直接赋值就行了
	smtpHost := emailCfg.Host
	smtpPort := emailCfg.Port
	smtpUser := emailCfg.Authuser
	smtpPass := emailCfg.Authpass
	
	toSendList := mailTo

	t := time.Now()
	year,month,day := t.Date()
	curTime := fmt.Sprintf("%d-%d-%d %d:%d",year,month,day,t.Hour(),t.Minute())
	auth := smtp.PlainAuth("", smtpUser,smtpPass,smtpHost)
	to := strings.Split(toSendList,",")
	header := make(map[string]string)
	header["From"] = smtpUser
	header["To"] = mailTo
	header["Date"] = curTime
	header["Subject"] = subject
	header["Content-Type"] = "text/html;charset=UTF-8"


	msg := ""
	for k,v := range header{
		msg += fmt.Sprintf("%s:%s\r\n",k,v)
	}
	msg += "\r\n"+body
	conn,err := tls.Dial("tcp",smtpHost+":"+smtpPort,nil)
	if err != nil {
		HandleWarning(err)
	}
	co,err := smtp.NewClient(conn,smtpHost)
	if err != nil {
		HandleWarning(err)
	}
	defer co.Close()
	if auth != nil {
		if ok,_ := co.Extension("AUTH");ok {
			if err = co.Auth(auth);err != nil {
				HandleError(err)
			}
		}
	}
	if err = co.Mail(smtpUser); err != nil {
		HandleError(err)
	}
	for _,addr := range to {
		if err = co.Rcpt(addr); err != nil {
			HandleWarning(err)
		}
	}
	w,err := co.Data()
	if err != nil {
		HandleWarning(err)
	}
	_,err = w.Write([]byte(msg))
	if err != nil {
		HandleWarning(err)
	}
	err = w.Close()
	if err != nil {
		HandleWarning(err)
	}
	co.Quit()
	return true,nil
}

func HandleWarning(err error) {
//怎么处理警告可以在这里定义
}
func HandleError(err error) {
//怎么处理错误可以在这里定义
}

2. 使用

func sendReviewMail(mailInfo MailInfo) (b bool,err error){
	subject := mailInfo.PrjNmEn + "项目 服务器申请"
	body := mailInfo.PrjNmEn + "项目,服务器申请已提交,请尽快审批"
	mailTo := "liubei-cto@xxx.com.cn"
	email := myMail.MyEmail{}
	b,err = email.SendEmail(mailTo,subject,body)
	if err != nil {
		return false,err
	}
	return b,nil
}

posted on 2022-04-09 17:31  运维开发玄德公  阅读(11)  评论(0编辑  收藏  举报  来源

导航