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" {
emails := strings.Split(email, ",")
for _, em := range emails {
sendEmail(em, alertMessage)
sendEmailMessage(em, alertMessage)
}
}
}

43
mail.go
View File

@ -1,27 +1,39 @@
package main
import (
"bytes"
"log"
"net/smtp"
)
func sendEmail(username, message string) {
c, err := smtp.Dial("127.0.0.1:25")
func sendEmail(mail_to, mail_default_authuser, mail_message string) {
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 {
log.Fatal(err)
}
defer c.Close()
// Set the sender and recipient.
c.Mail("info@wo-bisch.ch")
c.Rcpt(username)
// Send the email body.
wc, err := c.Data()
if err != nil {
log.Fatal(err)
}
defer wc.Close()
}
func sendEmailMessage(username, message string) {
mail_message := "To: " + username + `
From: info@wo-bisch.ch
Subject: ` + message + `
Lieber Benutzer von wo-bisch.ch
@ -30,8 +42,5 @@ Lieber Benutzer von wo-bisch.ch
--
wo-bisch.ch`
buf := bytes.NewBufferString(mail_message)
if _, err = buf.WriteTo(wc); err != nil {
log.Fatal(err)
}
sendEmail(username, "mail@wo-bisch.ch", mail_message)
}

View File

@ -3,8 +3,8 @@ package main
import (
"github.com/gomodule/redigo/redis"
"log"
"time"
"os"
"time"
)
var globalPool *redis.Pool
@ -29,7 +29,7 @@ func newPool() *redis.Pool {
// Dial is an application supplied function for creating and
// configuring a connection.
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 {
panic(err.Error())
}