You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.7 KiB

2 years ago
  1. package mail
  2. import (
  3. "crypto/tls"
  4. "fmt"
  5. "mime"
  6. "path/filepath"
  7. "strings"
  8. conf "gitea.baoapi.com/root/stu_uuos/config"
  9. "gopkg.in/gomail.v2"
  10. )
  11. type EMailClient struct {
  12. from string
  13. host string
  14. port int
  15. username string
  16. password string
  17. to []string
  18. subject []string
  19. content []string
  20. attach []string
  21. }
  22. func NewClient() *EMailClient {
  23. return &EMailClient{
  24. from: conf.GetConfig().Mail.Username,
  25. host: conf.GetConfig().Mail.Host,
  26. port: conf.GetConfig().Mail.Port,
  27. username: conf.GetConfig().Mail.Username,
  28. password: conf.GetConfig().Mail.Password,
  29. }
  30. }
  31. func (c *EMailClient) AddTo(to ...string) {
  32. c.to = append(c.to, to...)
  33. }
  34. func (c *EMailClient) AddSubject(subject ...string) {
  35. c.subject = append(c.subject, subject...)
  36. }
  37. func (c *EMailClient) AddContent(content ...string) {
  38. c.content = append(c.content, content...)
  39. }
  40. func (c *EMailClient) AddAttach(attach ...string) {
  41. c.attach = append(c.attach, attach...)
  42. }
  43. func (c *EMailClient) Send() error {
  44. m := gomail.NewMessage()
  45. m.SetHeader("From", c.from)
  46. m.SetHeader("To", c.to...)
  47. m.SetHeader("Subject", c.subject...)
  48. buf := strings.Builder{}
  49. for _, s := range c.content {
  50. buf.WriteString("<p>" + s + "</p>")
  51. }
  52. for _, v := range c.attach {
  53. fileName := filepath.Base(v)
  54. m.Attach(v, gomail.Rename(fileName),
  55. gomail.SetHeader(map[string][]string{
  56. "Content-Disposition": []string{
  57. fmt.Sprintf(`attachment; filename="%s"`, mime.QEncoding.Encode("UTF-8", fileName)),
  58. },
  59. }))
  60. }
  61. m.SetBody("text/html", buf.String())
  62. d := gomail.NewDialer(c.host, c.port, c.username, c.password)
  63. d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
  64. return d.DialAndSend(m)
  65. }