summaryrefslogtreecommitdiffhomepage
path: root/src/email/email.go
blob: 0f2c93d924a250972624038b56377a75387bd23d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package email

import (
	"crypto/tls"
	"fmt"
	"math/rand/v2"
	"net/smtp"
	"strconv"
	"time"
)

var Config struct {
	Disabled         bool
	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 {
	if Config.Disabled {
		return fault
	}

	msgid := strconv.FormatInt(rand.Int64(), 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
}