-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsmtp.go
91 lines (77 loc) · 2.46 KB
/
smtp.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
package main
import (
"crypto/tls"
"fmt"
"strings"
"github.com/wneessen/go-mail"
)
// sendEmail function modified to include the reply-to header
func sendEmail(smtpServer string, smtpPort int, username string, password string, from string, to []string, replyTo string, subject, body, bodyFile string, attachments []string, tlsMode string, noAuth bool) error {
// Create a new message
m := mail.NewMsg()
if err := m.From(from); err != nil {
return err
}
// Set recipient(s)
if err := m.To(to...); err != nil {
return err
}
// Set the subject
m.Subject(subject)
// Set the body
if bodyFile != "" {
m.SetBodyString(mail.TypeTextHTML, body)
} else {
m.SetBodyString(mail.TypeTextPlain, body)
}
// Add attachments
for _, attachment := range attachments {
m.AttachFile(attachment)
}
// Add the reply-to header if provided
if replyTo != "" {
if err := m.ReplyTo(replyTo); err != nil {
return err
}
}
clientOptions := []mail.Option{
mail.WithPort(smtpPort),
}
// Define client options
if !noAuth && (username != "" || password != "") {
clientOptions = append(
clientOptions,
mail.WithSMTPAuth(mail.SMTPAuthLogin),
mail.WithUsername(username),
mail.WithPassword(password),
)
}
// Conditionally add TLS options based on tlsMode
switch tlsMode {
case "none":
clientOptions = append(clientOptions, mail.WithTLSPolicy(mail.NoTLS))
case "tls-skip":
tlsSkipConfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: smtpServer,
}
clientOptions = append(clientOptions, mail.WithTLSConfig(tlsSkipConfig))
case "tls":
clientOptions = append(clientOptions, mail.WithTLSPolicy(mail.TLSMandatory))
}
// Create a new client using the options
c, err := mail.NewClient(smtpServer, clientOptions...)
if err != nil {
fmt.Printf("Failed to create SMTP client: %v", err)
}
if c == nil {
fmt.Printf("SMTP client is nil")
}
// Send the email
if err := c.DialAndSend(m); err != nil {
fmt.Printf("Error sending email: %v", err)
return err
}
fmt.Printf("\nEmail sent successfully to %s from %s\n", strings.Join(to, ", "), from)
return nil
}