a simple go tool vanity url server.
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.

mail.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package vain
  2. import (
  3. "bytes"
  4. "fmt"
  5. "net/mail"
  6. "net/smtp"
  7. )
  8. // A Mailer is a type that knows how to send smtp mail.
  9. type Mailer interface {
  10. Send(to mail.Address, subject, msg string) error
  11. }
  12. // NewMail returns *Send struct to be able to send smtp
  13. // or an error if it can't correctly parse the email address.
  14. func NewMail(from, host string, port int) (*Mail, error) {
  15. if _, err := mail.ParseAddress(from); err != nil {
  16. return nil, fmt.Errorf("can't parse an email address for 'from': %v", err)
  17. }
  18. r := &Mail{
  19. host: host,
  20. port: port,
  21. from: from,
  22. }
  23. return r, nil
  24. }
  25. // Mail stores information required to use smtp.
  26. type Mail struct {
  27. host string
  28. port int
  29. from string
  30. }
  31. // Send sends a smtp email using the host and port in the Mail struct and
  32. //returns an error if there was a problem sending the email.
  33. func (e Mail) Send(to mail.Address, subject, msg string) error {
  34. c, err := smtp.Dial(fmt.Sprintf("%s:%d", e.host, e.port))
  35. if err != nil {
  36. return fmt.Errorf("couldn't dial mail server: %v", err)
  37. }
  38. defer c.Close()
  39. if err := c.Mail(e.from); err != nil {
  40. return err
  41. }
  42. if err := c.Rcpt(to.String()); err != nil {
  43. return err
  44. }
  45. wc, err := c.Data()
  46. if err != nil {
  47. return fmt.Errorf("problem sending mail: %v", err)
  48. }
  49. buf := bytes.NewBufferString("Subject: " + subject + "\n\n" + msg)
  50. buf.WriteTo(wc)
  51. if err := c.Quit(); err != nil {
  52. return nil
  53. }
  54. return err
  55. }
  56. type mockMail struct {
  57. msg string
  58. }
  59. func (m *mockMail) Send(to mail.Address, subject, msg string) error {
  60. m.msg = msg
  61. return nil
  62. }