golang gomail发送邮件

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 := "xxxxxx@163.com"
	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 := `<html>
<body>
 {{.}}
</table>
</body>
</html>`

	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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值