vikunja-api/pkg/mail/mail.go

64 lines
1.6 KiB
Go
Raw Normal View History

2018-10-27 11:33:28 +02:00
package mail
import (
2018-10-31 13:42:38 +01:00
"code.vikunja.io/api/pkg/log"
2018-10-27 11:33:28 +02:00
"crypto/tls"
"github.com/spf13/viper"
"gopkg.in/gomail.v2"
"time"
)
// Queue is the mail queue
var Queue chan *gomail.Message
// StartMailDaemon starts the mail daemon
func StartMailDaemon() {
2018-10-28 17:11:13 +01:00
Queue = make(chan *gomail.Message, viper.GetInt("mailer.queuelength"))
2018-10-27 11:33:28 +02:00
if viper.GetString("mailer.host") == "" {
2018-10-31 13:42:38 +01:00
log.Log.Warning("Mailer seems to be not configured! Please see the config docs for more details.")
2018-10-27 11:33:28 +02:00
return
}
go func() {
d := gomail.NewDialer(viper.GetString("mailer.host"), viper.GetInt("mailer.port"), viper.GetString("mailer.username"), viper.GetString("mailer.password"))
d.TLSConfig = &tls.Config{InsecureSkipVerify: viper.GetBool("mailer.skiptlsverify")}
var s gomail.SendCloser
var err error
open := false
for {
select {
case m, ok := <-Queue:
if !ok {
return
}
if !open {
if s, err = d.Dial(); err != nil {
2018-10-31 13:42:38 +01:00
log.Log.Error("Error during connect to smtp server: %s", err)
2018-10-27 11:33:28 +02:00
}
open = true
}
if err := gomail.Send(s, m); err != nil {
2018-10-31 13:42:38 +01:00
log.Log.Error("Error when sending mail: %s", err)
2018-10-27 11:33:28 +02:00
}
// Close the connection to the SMTP server if no email was sent in
// the last 30 seconds.
case <-time.After(viper.GetDuration("mailer.queuetimeout") * time.Second):
if open {
if err := s.Close(); err != nil {
2018-10-31 13:42:38 +01:00
log.Log.Error("Error closing the mail server connection: %s\n", err)
2018-10-27 11:33:28 +02:00
}
2018-10-31 13:42:38 +01:00
log.Log.Infof("Closed connection to mailserver")
2018-10-27 11:33:28 +02:00
open = false
}
}
}
}()
}
// StopMailDaemon closes the mail queue channel, aka stops the daemon
func StopMailDaemon() {
close(Queue)
}