main.go (1774B)
1 package main 2 3 import ( 4 "encoding/base64" 5 "fmt" 6 "net/http" 7 "net/smtp" 8 "os" 9 "strings" 10 11 "code.dwrz.net/src/cmd/sgm/config" 12 "code.dwrz.net/src/pkg/gmail" 13 "code.dwrz.net/src/pkg/log" 14 ) 15 16 func main() { 17 var l = log.New(os.Stderr) 18 19 // Get the configuration. 20 cfg, err := config.New() 21 if err != nil { 22 l.Error.Fatalf("failed to get config: %v", err) 23 } 24 25 // Compose email. 26 var str strings.Builder 27 28 fmt.Fprintf(&str, "From: %s\r\n", cfg.From) 29 fmt.Fprintf(&str, "To: %s\r\n", cfg.To) 30 fmt.Fprintf(&str, "Subject: %s\r\n", cfg.Subject) 31 32 str.WriteString("MIME-Version: 1.0\n") 33 str.WriteString("Content-Type: multipart/mixed; boundary=\"=-=-=\"\n") 34 str.WriteString("\n") 35 str.WriteString("--=-=-=\n") 36 str.WriteString("Content-Type: text/plain; format=flowed\n") 37 str.WriteString("\n") 38 str.WriteString("\n") 39 str.WriteString(cfg.Text) 40 str.WriteString("\n") 41 str.WriteString("--=-=-=\n") 42 43 // Add the attachment, if provided. 44 if cfg.Attachment != "" { 45 data, err := os.ReadFile(cfg.Attachment) 46 if err != nil { 47 l.Error.Fatalf("failed to open file: %v", err) 48 } 49 50 fmt.Fprintf( 51 &str, 52 "Content-Type: %s\n", http.DetectContentType(data), 53 ) 54 fmt.Fprintf( 55 &str, 56 "Content-Disposition: attachment; filename=%s\n", 57 *&cfg.Attachment, 58 ) 59 str.WriteString("Content-Transfer-Encoding: base64\n") 60 fmt.Fprintf(&str, "Content-Description: %s\n", cfg.Attachment) 61 str.WriteString("\n") 62 str.WriteString(base64.StdEncoding.EncodeToString([]byte(data))) 63 str.WriteString("--=-=-=\n") 64 } 65 66 // Send the email. 67 if err := smtp.SendMail( 68 gmail.Address, 69 &gmail.Auth{ 70 Username: cfg.User, 71 Password: cfg.Pass, 72 }, 73 cfg.From, 74 strings.Split(cfg.To, ","), 75 []byte(str.String()), 76 ); err != nil { 77 l.Error.Fatalf("failed to send email: %v", err) 78 } 79 }