config.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package smtp
  5. import (
  6. "crypto/tls"
  7. "fmt"
  8. "net/smtp"
  9. "github.com/pkg/errors"
  10. )
  11. // Config contains configuration for SMTP authentication.
  12. //
  13. // ⚠️ WARNING: Change to the field name must preserve the INI key name for backward compatibility.
  14. type Config struct {
  15. Auth string
  16. Host string
  17. Port int
  18. AllowedDomains string
  19. TLS bool `ini:"tls"`
  20. SkipVerify bool
  21. }
  22. func (c *Config) doAuth(auth smtp.Auth) error {
  23. client, err := smtp.Dial(fmt.Sprintf("%s:%d", c.Host, c.Port))
  24. if err != nil {
  25. return err
  26. }
  27. defer client.Close()
  28. if err = client.Hello("gogs"); err != nil {
  29. return err
  30. }
  31. if c.TLS {
  32. if ok, _ := client.Extension("STARTTLS"); ok {
  33. if err = client.StartTLS(&tls.Config{
  34. InsecureSkipVerify: c.SkipVerify,
  35. ServerName: c.Host,
  36. }); err != nil {
  37. return err
  38. }
  39. } else {
  40. return errors.New("SMTP server does not support TLS")
  41. }
  42. }
  43. if ok, _ := client.Extension("AUTH"); ok {
  44. if err = client.Auth(auth); err != nil {
  45. return err
  46. }
  47. return nil
  48. }
  49. return errors.New("unsupported SMTP authentication method")
  50. }