diff --git a/test/smtp/main.go b/test/smtp/main.go new file mode 100644 index 0000000..24bdf39 --- /dev/null +++ b/test/smtp/main.go @@ -0,0 +1,31 @@ +package main + +import ( + "fmt" + + "github.com/go-core-stack/core/utils/smtp" +) + +func main() { + config := smtp.Config{ + Host: "smtp.gmail.com", + Port: "587", + Sender: "info.psethi@gmail.com", + SenderName: "Prabhjot Sethi", + ReplyTo: "prabhjot.sethi@gmail.com", + Password: "ixytccsbvusoivjy", + } + + client := smtp.New(config) + + err := client.Send(&smtp.Message{ + Receivers: []string{"prabhjot.sethi@gmail.com", "prabhjot.lists@gmail.com"}, + Subject: "Test Email", + Body: "This is a test email sent using the smtp package.", + Html: false, + }) + + if err != nil { + fmt.Printf("failed to send email: %v\n", err) + } +} diff --git a/utils/smtp/smtp.go b/utils/smtp/smtp.go index 23faffb..50ddba0 100644 --- a/utils/smtp/smtp.go +++ b/utils/smtp/smtp.go @@ -23,6 +23,14 @@ type Config struct { // Sender email address / username for authentication Sender string + // Sender Descriptive Name to be included in the email + SenderName string + + // reply-to email address as typically sender email would + // be device control and typically would be no-reply, + // if empty means reply-to is not configured + ReplyTo string + // Password for authenticating the sender with smtp server Password string } @@ -69,7 +77,29 @@ func (c *Client) Send(m *Message) error { mime = "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n" } - message := fmt.Appendf(nil, "Subject: %s\n%s%s", m.Subject, mime, m.Body) + var header string + if c.config.SenderName != "" { + // If sender name is provided, use it in the From header. + header = fmt.Sprintf("From: %s <%s>\r\n", c.config.SenderName, c.config.Sender) + } else { + // If sender name is not provided, use only the email address. + header = fmt.Sprintf("From: <%s>\r\n", c.config.Sender) + } + + if c.config.ReplyTo != "" { + // If reply-to is configured, add it to the headers. + header += fmt.Sprintf("Reply-To: %s\r\n", c.config.ReplyTo) + } + + if len(m.Receivers) > 0 { + header += fmt.Sprintf("To: %s", m.Receivers[0]) + for _, receiver := range m.Receivers[1:] { + header += fmt.Sprintf(", %s", receiver) + } + header += "\r\n" + } + + message := fmt.Appendf(nil, "%sSubject: %s\n%s%s", header, m.Subject, mime, m.Body) // Sending email. err := smtp.SendMail(c.endpoint, auth, c.config.Sender, m.Receivers, message) if err != nil {