1 Star 0 Fork 0

ww156/notify

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
email.go 2.57 KB
Copy Edit Raw Blame History
ww156 authored 2021-12-18 14:53 . 添加邮件模板字符串解析
package email
import (
"context"
"fmt"
"net/mail"
"path/filepath"
"gitee.com/childewang/gomail"
"gitee.com/childewang/notify/template"
"go.uber.org/zap"
)
var (
DefaultTemplate = filepath.Join("..", "template", "email.tmpl")
)
// Email implements a Notifier for email notifications.
type Email struct {
conf *EmailConfig
logger *zap.Logger
}
// New create Email instance.
func New(c *EmailConfig, l *zap.Logger) *Email {
return &Email{conf: c, logger: l}
}
// Type the type of a Notifier
func (e *Email) Type() string {
return "EMAIL"
}
// Notify send an email
func (e *Email) Notify(ctx context.Context) error {
var (
err error
)
conf := e.conf
// 发件人
from_addrs, err := mail.ParseAddressList(conf.From)
if err != nil {
return fmt.Errorf("parse 'from' addresses\n%w", err)
}
if len(from_addrs) != 1 {
return fmt.Errorf("must be exactly one 'from' address (got: %d)\n%w", len(from_addrs), err)
}
// 收件人
to_addrs, err := mail.ParseAddressList(conf.To)
if err != nil {
return fmt.Errorf("parse 'to' addresses\n%w", err)
}
// 设置邮件头
m := gomail.NewMessage()
m.SetHeader("From", from_addrs[0].Address)
m.SetHeader("To", parseEmilAddress(to_addrs)...)
// 抄送人
cc := e.conf.Cc
if cc != "" {
cc_addrs, err := mail.ParseAddressList(cc)
if err != nil {
return fmt.Errorf("parse 'cc' addresses\n%w", err)
}
m.SetHeader("Cc", parseEmilAddress(cc_addrs)...)
}
// 密送人
bcc := e.conf.Bcc
if bcc != "" {
bcc_addrs, err := mail.ParseAddressList(bcc)
if err != nil {
return fmt.Errorf("parse 'bcc' addresses\n%w", err)
}
m.SetHeader("Bcc", parseEmilAddress(bcc_addrs)...)
}
// set the email Subject
if conf.Subject == "" {
conf.Subject = conf.From
}
m.SetHeader("Subject", conf.Subject)
if conf.Template != "" {
html, err := template.ExecuteTemplateString(conf.Template, conf.Data)
if err != nil {
return fmt.Errorf("parse html template\n%w", err)
}
m.SetBody("text/html", html)
} else if conf.TemplateFile != "" {
html, err := template.ExecuteTemplate(conf.TemplateFile, conf.Data)
if err != nil {
return fmt.Errorf("parse html template\n%w", err)
}
m.SetBody("text/html", html)
} else {
m.SetBody("text/html", "")
}
d := gomail.NewDialer(conf.EmailServer.Host, conf.EmailServer.Port, conf.AuthUsername, string(conf.AuthPassword))
if err := d.DialAndSend(m); err != nil {
return fmt.Errorf("send emai \n%w", err)
}
return nil
}
func parseEmilAddress(addresses []*mail.Address) []string {
arr := []string{}
for _, item := range addresses {
arr = append(arr, item.String())
}
return arr
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/childewang/notify.git
git@gitee.com:childewang/notify.git
childewang
notify
notify
34056af3f771

Search

344bd9b3 5694891 D2dac590 5694891