-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
96 lines (77 loc) · 2.19 KB
/
main.go
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"bytes"
"encoding/base64"
"fmt"
"log"
"mime/multipart"
"net/smtp"
"os"
"path/filepath"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file")
}
email := os.Getenv("EMAIL")
password := os.Getenv("PASSWORD")
toEmail := os.Getenv("TO_EMAIL")
subject := "CONVERT"
booksDir := os.Getenv("BOOKS_DIR")
if booksDir == "" {
log.Fatalf("Books directory not specified in .env file")
}
if len(os.Args) < 2 {
log.Fatalf("Please specify the file name as an argument in quotes")
}
filename := os.Args[1]
attachmentPath := filepath.Join(booksDir, filename)
attachmentData, err := os.ReadFile(attachmentPath)
if err != nil {
log.Fatalf("Error reading file: %s", err)
}
smtpHost := "smtp.gmail.com"
smtpPort := "587"
var body bytes.Buffer
writer := multipart.NewWriter(&body)
headers := map[string]string{
"From": email,
"To": toEmail,
"Subject": subject,
"MIME-Version": "1.0",
"Content-Type": fmt.Sprintf(`multipart/mixed; boundary="%s"`, writer.Boundary()),
}
for key, value := range headers {
body.WriteString(fmt.Sprintf("%s: %s\r\n", key, value))
}
body.WriteString("\r\n")
part, err := writer.CreatePart(nil)
if err != nil {
log.Fatalf("Error creating text part: %s", err)
}
part.Write([]byte(""))
part, err = writer.CreatePart(map[string][]string{
"Content-Type": {fmt.Sprintf(`application/octet-stream; name="%s"`, filepath.Base(attachmentPath))},
"Content-Transfer-Encoding": {"base64"},
"Content-Disposition": {fmt.Sprintf(`attachment; filename="%s"`, filepath.Base(attachmentPath))},
})
if err != nil {
log.Fatalf("Error creating attachment part: %s", err)
}
encoder := base64.NewEncoder(base64.StdEncoding, part)
_, err = encoder.Write(attachmentData)
if err != nil {
log.Fatalf("Error encoding file content: %s", err)
}
encoder.Close()
writer.Close()
auth := smtp.PlainAuth("", email, password, smtpHost)
err = smtp.SendMail(smtpHost+":"+smtpPort, auth, email, []string{toEmail}, body.Bytes())
if err != nil {
log.Fatalf("Error sending email: %s", err)
} else {
log.Println("Email sent successfully!")
}
}