summaryrefslogtreecommitdiffhomepage
path: root/lib
diff options
context:
space:
mode:
authorThomas Voss <mail@thomasvoss.com> 2024-08-12 23:58:46 +0200
committerThomas Voss <mail@thomasvoss.com> 2024-08-12 23:58:54 +0200
commit71937c1079a77e0b38dae00662ab2041c3e28f77 (patch)
tree1e861548d89d9a57c873fe968b395ba5518f4770 /lib
parent17dd2383d5f17280288087da76803f6d3e9a5aae (diff)
Add email support
Diffstat (limited to 'lib')
-rw-r--r--lib/email/email.go75
1 files changed, 75 insertions, 0 deletions
diff --git a/lib/email/email.go b/lib/email/email.go
new file mode 100644
index 0000000..f6d6673
--- /dev/null
+++ b/lib/email/email.go
@@ -0,0 +1,75 @@
+package email
+
+import (
+ "crypto/tls"
+ "fmt"
+ "math/rand"
+ "net/smtp"
+ "strconv"
+ "time"
+)
+
+var Config struct {
+ Host string
+ Port int
+ ToAddr, FromAddr string
+ Password string
+}
+
+const emailTemplate = `From: %s
+To: %s
+Subject: %s
+Date: %s
+Content-Type: text/plain; charset=UTF-8
+MIME-Version: 1.0
+Message-ID: <%s>
+
+%s`
+
+func ServerError(fault error) error {
+ r := rand.New(rand.NewSource(time.Now().UnixNano()))
+ msgid := strconv.FormatInt(r.Int63(), 10) + "@" + Config.Host
+ msg := fmt.Sprintf(emailTemplate, Config.FromAddr, Config.ToAddr,
+ "Error Report", time.Now().Format(time.RFC1123Z), msgid, fault)
+
+ tlsConfig := &tls.Config{
+ InsecureSkipVerify: false,
+ ServerName: Config.Host,
+ }
+
+ hostWithPort := Config.Host + ":" + strconv.Itoa(Config.Port)
+ conn, err := tls.Dial("tcp", hostWithPort, tlsConfig)
+ if err != nil {
+ return err
+ }
+
+ client, err := smtp.NewClient(conn, Config.Host)
+ if err != nil {
+ return err
+ }
+ defer client.Close()
+
+ auth := smtp.PlainAuth("", Config.FromAddr, Config.Password, Config.Host)
+ if err := client.Auth(auth); err != nil {
+ return err
+ }
+
+ if err := client.Mail(Config.FromAddr); err != nil {
+ return err
+ }
+
+ if err := client.Rcpt(Config.ToAddr); err != nil {
+ return err
+ }
+
+ wc, err := client.Data()
+ if err != nil {
+ return err
+ }
+ defer wc.Close()
+
+ if _, err = wc.Write([]byte(msg)); err != nil {
+ return err
+ }
+ return nil
+}