woodpecker_mailer/main.go

77 lines
1.8 KiB
Go

package main
import (
"crypto/tls"
"fmt"
"html/template"
"net/mail"
"net/smtp"
"os"
"strings"
)
// "Send As" information
func main() {
var (
username = os.Getenv("PLUGIN_USER")
password = os.Getenv("PLUGIN_PASSWORD")
to = os.Getenv("PLUGIN_TO")
subject = os.Getenv("PLUGIN_SUBJECT")
body = os.Getenv("PLUGIN_TEXT")
from_addr = os.Getenv("PLUGIN_FROM")
from_name = os.Getenv("PLUGIN_FROM_NAME")
)
if username == "" || password == "" || to == "" || subject == "" || body == "" {
panic("'user', 'password', 'to', 'subject', and 'text' are mandatory!")
}
if username == "" || password == "" || to == "" || subject == "" || body == "" {
panic("'user', 'password', 'to', 'subject', and 'text' are mandatory!")
}
const gmail = "smtp.gmail.com:587"
sanitizedBody := template.HTMLEscapeString(body)
fmt.Println("Authenticateing...")
auth := smtp.PlainAuth("", username, password, "smtp.gmail.com")
smtpConnection, err := smtp.Dial(gmail)
if err != nil {
panic(err)
}
if err := smtpConnection.StartTLS(&tls.Config{ServerName: "smtp.gmail.com"}); err != nil {
panic(err)
}
if err := smtpConnection.Auth(auth); err != nil {
panic(err)
}
from := mail.Address{Name: from_name, Address: from_addr}
header := make(map[string]string)
header["From"] = from.String()
header["To"] = to
header["Subject"] = subject
// Convert the header map to a string and attach the body to it
var message string
for key, value := range header {
message += fmt.Sprintf("%s: %s\r\n", key, value)
}
message += "\r\n" + sanitizedBody + "\r\n"
fmt.Println("Senting an email to user")
rcpts := strings.Split(to, ",")
err = smtp.SendMail(gmail, auth, from_addr, rcpts, []byte(message))
if err != nil {
panic(err)
}
smtpConnection.Quit()
fmt.Println("Done")
}