Example #1
0
func (s *EmailServer) queueToDb() {

	var em email.Email
	wait, _ := time.ParseDuration("5m")

	for {
		d, err := s.queue.PopWait(wait)
		panik.On(err)
		if len(d) > 0 {
			// read from queue
			//err = ds.LoadStruct(&em, d)
			err = ds.Load(&em, d)
			if err != nil {
				log.Error("Error reading email from queue", "email", em, "error", err)
				panik.On(err)
			}

			// save to db
			m := Message{
				Data:      string(d),
				Priority:  em.Priority,
				CreatedAt: time.Now().Unix(),
				SendAfter: em.SendAfter,
			}
			err = s.dbo.Create(&m).Error
			if err != nil { // on error, put back in queue
				s.queue.Push(d)
				panik.On(err)
			}
		}
	}
}
Example #2
0
func (s *EmailServer) dispatchMessage(m *Message) error {
	var e email.Email
	//err := ds.LoadStruct(&e, []byte(m.Data))
	err := ds.Load(&e, []byte(m.Data))
	if err != nil {
		return err
	}

	// Merge the To, Cc, and Bcc fields
	to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
	to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
	for i := 0; i < len(to); i++ {
		addr, err := mail.ParseAddress(to[i])
		if err != nil {
			return err
		}
		to[i] = addr.Address
	}

	// Check to make sure there is at least one recipient and one "From" address
	if e.From == "" || len(to) == 0 {
		return errors.New("Must specify at least one From address and one To address")
	}
	from, err := mail.ParseAddress(e.From)
	if err != nil {
		return err
	}
	raw, err := e.Bytes()
	if err != nil {
		return err
	}

	return smtp.SendMail(s.address, s.auth, from.Address, to, raw)
}