wireguard-dashboard/utils/mail.go

83 lines
1.9 KiB
Go
Raw Permalink Normal View History

2024-03-22 11:40:34 +08:00
package utils
import (
"crypto/tls"
"errors"
2024-03-22 11:40:34 +08:00
"fmt"
"github.com/jordan-wright/email"
2024-03-22 11:40:34 +08:00
"mime"
"net/smtp"
"net/textproto"
2024-03-22 11:40:34 +08:00
"path/filepath"
"wireguard-dashboard/config"
)
type mail struct {
*email.Email
addr string
auth smtp.Auth
2024-03-22 11:40:34 +08:00
}
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
2024-03-22 11:40:34 +08:00
}
func (m *mail) VerifyConfig() (err error) {
if m == nil {
return errors.New("邮件客户端初始化失败")
}
2024-03-22 11:40:34 +08:00
if m.auth == nil || m.addr == "" {
return errors.New("邮件客户端未完成初始化")
2024-03-22 11:40:34 +08:00
}
return nil
2024-03-22 11:40:34 +08:00
}
// SendMail
// @description: 发送附件
2024-03-22 11:40:34 +08:00
// @receiver m
// @param to
2024-03-22 11:40:34 +08:00
// @param subject
// @param attacheFilePath
2024-03-22 11:40:34 +08:00
// @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
}
2024-03-22 11:40:34 +08:00
if config.Config.Mail.SkipTls {
return m.Send(m.addr, m.auth)
2024-03-22 11:40:34 +08:00
}
tlsConfig := &tls.Config{}
tlsConfig.InsecureSkipVerify = config.Config.Mail.SkipTls
tlsConfig.ServerName = config.Config.Mail.Host
return m.SendWithTLS(m.addr, m.auth, tlsConfig)
2024-03-22 11:40:34 +08:00
}
// getFileName
// @description: 获取文件名
// @receiver m
// @param filePath
// @return string
func (m *mail) getFileName(filePath string) string {
2024-03-22 11:40:34 +08:00
return filepath.Base(filePath)
}