86 lines
2.0 KiB
Go
86 lines
2.0 KiB
Go
package utils
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"fmt"
|
|
"gitee.ltd/lxh/logger/log"
|
|
"gopkg.in/gomail.v2"
|
|
"mime"
|
|
"path/filepath"
|
|
"wireguard-dashboard/config"
|
|
)
|
|
|
|
type mail struct {
|
|
md *gomail.Dialer
|
|
}
|
|
|
|
func Mail() mail {
|
|
mailDialer := gomail.NewDialer(config.Config.Mail.Host, config.Config.Mail.Port, config.Config.Mail.User, config.Config.Mail.Password)
|
|
mailDialer.TLSConfig = &tls.Config{
|
|
InsecureSkipVerify: config.Config.Mail.SkipTls,
|
|
}
|
|
return mail{mailDialer}
|
|
}
|
|
|
|
// SendMail
|
|
// @description: 发送普通邮件
|
|
// @receiver mail
|
|
// @param subject
|
|
// @param toAddress
|
|
// @param content
|
|
// @return err
|
|
func (m mail) SendMail(subject, toAddress, content string) (err error) {
|
|
msg := gomail.NewMessage()
|
|
msg.SetHeader("From", msg.FormatAddress(m.md.Username, "wireguard-dashboard"))
|
|
msg.SetHeader("To", toAddress)
|
|
msg.SetHeader("Subject", subject)
|
|
msg.SetBody("text/plain", content)
|
|
|
|
if err = m.md.DialAndSend(msg); err != nil {
|
|
log.Errorf("发送普通邮件失败: %v", err.Error())
|
|
return
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
// SendMailWithAttach
|
|
// @description: 发送并携带附件
|
|
// @receiver m
|
|
// @param subject
|
|
// @param toAddress
|
|
// @param content
|
|
// @param attachPath
|
|
// @return err
|
|
func (m mail) SendMailWithAttach(subject, toAddress, content, attachPath string) (err error) {
|
|
msg := gomail.NewMessage()
|
|
msg.SetHeader("From", msg.FormatAddress(m.md.Username, "wireguard-dashboard"))
|
|
msg.SetHeader("To", toAddress)
|
|
msg.SetHeader("Subject", subject)
|
|
msg.SetBody("text/plain", content)
|
|
|
|
rename := m.getFileName(attachPath)
|
|
|
|
msg.Attach(attachPath, gomail.Rename(rename), gomail.SetHeader(map[string][]string{
|
|
"Content-Disposition": {
|
|
fmt.Sprintf(`attachment; filename="%s"`, mime.BEncoding.Encode("UTF-8", rename)),
|
|
},
|
|
}))
|
|
|
|
if err = m.md.DialAndSend(msg); err != nil {
|
|
log.Errorf("发送普通邮件失败: %v", err.Error())
|
|
return
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
// getFileName
|
|
// @description: 获取文件名
|
|
// @receiver m
|
|
// @param filePath
|
|
// @return string
|
|
func (m mail) getFileName(filePath string) string {
|
|
return filepath.Base(filePath)
|
|
}
|