sender.go

 1package sender
 2
 3import (
 4	"fmt"
 5	"net/smtp"
 6
 7	"github.com/andrinoff/email-cli/config" // Import the local config package
 8)
 9
10// SendEmail sends an email using the provided configuration and content.
11func SendEmail(cfg *config.Config, to []string, subject, body string) error {
12	var smtpHost, smtpPort string
13
14	switch cfg.ServiceProvider {
15	case "gmail":
16		smtpHost = "smtp.gmail.com"
17		smtpPort = "587"
18	case "icloud":
19		smtpHost = "smtp.mail.me.com"
20		smtpPort = "587"
21	default:
22		return fmt.Errorf("unsupported service provider: %s", cfg.ServiceProvider)
23	}
24
25	auth := smtp.PlainAuth("", cfg.Email, cfg.Password, smtpHost)
26	msg := fmt.Sprintf("From: %s <%s>\r\n", "Some Name", cfg.Email) +
27		fmt.Sprintf("To: %s\r\n", to[0]) +
28		fmt.Sprintf("Subject: %s\r\n", subject) +
29		"\r\n" + // An empty line is required between headers and the body.
30		body
31
32	addr := smtpHost + ":" + smtpPort
33	return smtp.SendMail(addr, auth, cfg.Email, to, []byte(msg))
34}