Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions test/smtp/main.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
32 changes: 31 additions & 1 deletion utils/smtp/smtp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down