2021-03-23 21:58:17 +00:00
|
|
|
package email
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2023-03-07 01:06:46 +00:00
|
|
|
"crypto/tls"
|
2021-03-23 21:58:17 +00:00
|
|
|
"fmt"
|
2023-03-07 01:06:46 +00:00
|
|
|
"net/smtp"
|
2021-03-23 21:58:17 +00:00
|
|
|
"os/exec"
|
|
|
|
)
|
|
|
|
|
2023-03-07 01:06:46 +00:00
|
|
|
const (
|
2023-03-09 06:33:31 +00:00
|
|
|
from = "root@tilde.town"
|
|
|
|
SMTPHost = "smtp.zoho.com"
|
|
|
|
SMTPPort = 465
|
2023-03-07 01:06:46 +00:00
|
|
|
)
|
|
|
|
|
2021-03-23 21:58:17 +00:00
|
|
|
func SendLocalEmail(username, subject, body string) error {
|
|
|
|
cmd := exec.Command("/usr/sbin/sendmail", username)
|
|
|
|
cmd.Stdin = bytes.NewBufferString(fmt.Sprintf("Subject: %s\n\n%s", subject, body))
|
|
|
|
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
|
|
return fmt.Errorf("failed to send local email: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2023-03-07 01:06:46 +00:00
|
|
|
|
|
|
|
type ExternalMailer struct {
|
|
|
|
Password string
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewExternalMailer(pw string) *ExternalMailer {
|
|
|
|
if pw == "" {
|
|
|
|
panic("why?")
|
|
|
|
}
|
|
|
|
return &ExternalMailer{
|
|
|
|
Password: pw,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *ExternalMailer) Send(address, subject, body string) error {
|
2023-03-09 06:33:31 +00:00
|
|
|
headers := map[string]string{
|
|
|
|
"From": from,
|
|
|
|
"To": address,
|
|
|
|
"Subject": subject,
|
|
|
|
}
|
|
|
|
|
|
|
|
message := ""
|
|
|
|
for k, v := range headers {
|
|
|
|
message += fmt.Sprintf("%s: %s\r\n", k, v)
|
|
|
|
}
|
|
|
|
message += "\r\n" + body
|
|
|
|
|
|
|
|
auth := smtp.PlainAuth("", from, m.Password, SMTPHost)
|
2023-03-07 01:06:46 +00:00
|
|
|
|
|
|
|
server := fmt.Sprintf("%s:%d", SMTPHost, SMTPPort)
|
|
|
|
|
|
|
|
tlsconf := &tls.Config{
|
|
|
|
InsecureSkipVerify: true,
|
|
|
|
ServerName: server,
|
|
|
|
}
|
|
|
|
|
|
|
|
conn, err := tls.Dial("tcp", server, tlsconf)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
c, err := smtp.NewClient(conn, SMTPHost)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = c.Auth(auth); err != nil {
|
|
|
|
return fmt.Errorf("auth failed for smtp: %w", err)
|
|
|
|
}
|
|
|
|
|
2023-03-10 03:21:12 +00:00
|
|
|
if err = c.Mail(from); err != nil {
|
2023-03-07 01:06:46 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = c.Rcpt(address); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
w, err := c.Data()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-03-10 03:21:12 +00:00
|
|
|
_, err = w.Write([]byte(message))
|
2023-03-07 01:06:46 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Close()
|
|
|
|
c.Quit()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|