refactor email send functions

This commit is contained in:
Joerg Lehmann 2022-07-13 19:30:59 +02:00
parent 6d7b0871ad
commit 683a8a5fc1
3 changed files with 34 additions and 25 deletions

View File

@ -78,7 +78,7 @@ func sendAlert(deveui string, alertMessage string) {
if emailalarmactive == "1" { if emailalarmactive == "1" {
emails := strings.Split(email, ",") emails := strings.Split(email, ",")
for _, em := range emails { for _, em := range emails {
sendEmail(em, alertMessage) sendEmailMessage(em, alertMessage)
} }
} }
} }

43
mail.go
View File

@ -1,27 +1,39 @@
package main package main
import ( import (
"bytes"
"log" "log"
"net/smtp" "net/smtp"
) )
func sendEmail(username, message string) { func sendEmail(mail_to, mail_default_authuser, mail_message string) {
c, err := smtp.Dial("127.0.0.1:25") var auth smtp.Auth
if getenv("MAILSERVER_USER", "") != "" {
// Set up authentication information.
auth = smtp.PlainAuth(
"",
getenv("MAILSERVER_USER", ""),
getenv("MAILSERVER_PASSWORD", ""),
getenv("MAILSERVER_HOST", "127.0.0.1"),
)
}
// Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step.
err := smtp.SendMail(
getenv("MAILSERVER_HOST", "127.0.0.1")+":"+getenv("MAILSERVER_PORT", "25"),
auth,
getenv("MAILSERVER_USER", mail_default_authuser),
[]string{mail_to},
[]byte(mail_message),
)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer c.Close() }
// Set the sender and recipient.
c.Mail("info@wo-bisch.ch") func sendEmailMessage(username, message string) {
c.Rcpt(username)
// Send the email body.
wc, err := c.Data()
if err != nil {
log.Fatal(err)
}
defer wc.Close()
mail_message := "To: " + username + ` mail_message := "To: " + username + `
From: info@wo-bisch.ch
Subject: ` + message + ` Subject: ` + message + `
Lieber Benutzer von wo-bisch.ch Lieber Benutzer von wo-bisch.ch
@ -30,8 +42,5 @@ Lieber Benutzer von wo-bisch.ch
-- --
wo-bisch.ch` wo-bisch.ch`
buf := bytes.NewBufferString(mail_message) sendEmail(username, "mail@wo-bisch.ch", mail_message)
if _, err = buf.WriteTo(wc); err != nil {
log.Fatal(err)
}
} }

View File

@ -3,8 +3,8 @@ package main
import ( import (
"github.com/gomodule/redigo/redis" "github.com/gomodule/redigo/redis"
"log" "log"
"time"
"os" "os"
"time"
) )
var globalPool *redis.Pool var globalPool *redis.Pool
@ -29,7 +29,7 @@ func newPool() *redis.Pool {
// Dial is an application supplied function for creating and // Dial is an application supplied function for creating and
// configuring a connection. // configuring a connection.
Dial: func() (redis.Conn, error) { Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", getenv("REDIS_CONNECTION_STRING",":6379")) c, err := redis.Dial("tcp", getenv("REDIS_CONNECTION_STRING", ":6379"))
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
} }