You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
958 B
52 lines
958 B
package nwmail
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"fmt"
|
|
"io"
|
|
"net/smtp"
|
|
)
|
|
|
|
type Client struct {
|
|
SMTPHostname string
|
|
SMTPPort int
|
|
PreferSTARTTLS bool
|
|
}
|
|
|
|
func NewClient(smtpHostname string, smtpPort int, preferSTARTTLS bool) *Client {
|
|
return &Client{SMTPHostname: smtpHostname, SMTPPort: smtpPort, PreferSTARTTLS: preferSTARTTLS}
|
|
}
|
|
|
|
func (c Client) SendMail(localName string, mail *Mail) error {
|
|
conn, err := smtp.Dial(fmt.Sprintf("%s:%d", c.SMTPHostname, c.SMTPPort))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
conn.Hello(localName)
|
|
|
|
if c.PreferSTARTTLS {
|
|
if hasStartTLS, _ := conn.Extension("STARTTLS"); hasStartTLS {
|
|
err = conn.StartTLS(&tls.Config{ServerName: c.SMTPHostname})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
conn.Mail(mail.sender)
|
|
for _, recipient := range mail.recipients {
|
|
conn.Rcpt(recipient)
|
|
}
|
|
|
|
writer, err := conn.Data()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
io.Copy(writer, mail.Buffer())
|
|
writer.Close()
|
|
|
|
return conn.Quit()
|
|
}
|