wireguard-dashboard/utils/mail.go

83 lines
1.9 KiB
Go

package utils
import (
"crypto/tls"
"errors"
"fmt"
"github.com/jordan-wright/email"
"mime"
"net/smtp"
"net/textproto"
"path/filepath"
"wireguard-dashboard/config"
)
type mail struct {
*email.Email
addr string
auth smtp.Auth
}
func Mail() *mail {
var m mail
em := email.NewEmail()
m.Email = em
m.auth = smtp.PlainAuth("", config.Config.Mail.User, config.Config.Mail.Password, config.Config.Mail.Host)
m.addr = fmt.Sprintf("%s:%d", config.Config.Mail.Host, config.Config.Mail.Port)
return &m
}
func (m *mail) VerifyConfig() (err error) {
if m == nil {
return errors.New("邮件客户端初始化失败")
}
if m.auth == nil || m.addr == "" {
return errors.New("邮件客户端未完成初始化")
}
return nil
}
// SendMail
// @description: 发送附件
// @receiver m
// @param to
// @param subject
// @param attacheFilePath
// @return err
func (m *mail) SendMail(to, subject, content, attacheFilePath string) (err error) {
m.From = fmt.Sprintf("wg-dashboard <%s>", config.Config.Mail.User)
m.To = []string{to}
m.Subject = subject
m.Text = []byte(content)
if attacheFilePath != "" {
atch, err := m.AttachFile(attacheFilePath)
if err != nil {
return fmt.Errorf("读取附件文件失败: %v", err.Error())
}
emHeader := textproto.MIMEHeader{}
emHeader.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, mime.BEncoding.Encode("UTF-8", m.getFileName(attacheFilePath))))
atch.Header = emHeader
}
if config.Config.Mail.SkipTls {
return m.Send(m.addr, m.auth)
}
tlsConfig := &tls.Config{}
tlsConfig.InsecureSkipVerify = config.Config.Mail.SkipTls
tlsConfig.ServerName = config.Config.Mail.Host
return m.SendWithTLS(m.addr, m.auth, tlsConfig)
}
// getFileName
// @description: 获取文件名
// @receiver m
// @param filePath
// @return string
func (m *mail) getFileName(filePath string) string {
return filepath.Base(filePath)
}