golang gomail 메일 보내기

2215 단어 golang
goMail 파일 보내기 Demo
package main

import (
	"fmt"
	"bytes"
	"strings"
	"strconv"
	"io/ioutil"
	"html/template"

	"github.com/go-gomail/gomail"
	"golang.org/x/text/transform"
	"golang.org/x/text/encoding/simplifiedchinese"
)
type (
	EmailNotify struct {
		SmtpS   string
		SmtpP   int
		Fromer  string
		Toers   []string
		Ccers   []string
		EUser   string
		Epasswd string
	}
)
var DefaultEmail *EmailNotify
func init() {
	smtp_s_str := "smtp.163.com"
	smtp_p_str := "25"
	sender_str := "[email protected]"
	passwd_str := "xxxxxx"

	receivers := []string{}
	receiversStr := ""
	for _, receiverStr := range strings.Split(receiversStr, ";") {
		receivers = append(receivers, strings.TrimSpace(receiverStr))
	}

	smtp_p_int, _ := strconv.Atoi(smtp_p_str)

	DefaultEmail = &EmailNotify{
		SmtpS:   smtp_s_str,
		SmtpP:   smtp_p_int,
		Fromer:  sender_str,
		Toers:   receivers,
		Ccers:   []string{},
		EUser:   strings.Split(sender_str, "@")[0],
		Epasswd: passwd_str,
	}
}

func (en *EmailNotify) SendNotifyWithFile(title, content, filePath, newName string) bool {
	msg := gomail.NewMessage(gomail.SetCharset("utf-8"))
	msg.SetHeader("From", en.Fromer)
	msg.SetHeader("To", en.Toers...)
	msg.SetHeader("Subject", title)

	msg.SetBody("text/html", en.renderNotify(content))

	// 
	fileName, _ := Utf8ToGbk([]byte(newName))
	msg.Attach(filePath, gomail.Rename(string(fileName)))

	mailer := gomail.NewDialer(en.SmtpS, en.SmtpP, en.EUser, en.Epasswd)
	if err := mailer.DialAndSend(msg); err != nil {
		fmt.Println(err.Error())
		panic(err)
	}
	return true
}

func (en *EmailNotify) renderNotify(content string) string {
	tplStr := `

 {{.}}


`

	outBuf := &bytes.Buffer{}
	tpl := template.New("email notify template")
	tpl, _ = tpl.Parse(tplStr)
	tpl.Execute(outBuf, content)

	return outBuf.String()
}
func Utf8ToGbk(s []byte) ([]byte, error) {
	reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewEncoder())
	d, e := ioutil.ReadAll(reader)
	if e != nil {
		return nil, e
	}
	return d, nil
}

좋은 웹페이지 즐겨찾기