55 lines
1.0 KiB
Go
55 lines
1.0 KiB
Go
package vain
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"net/mail"
|
|
"net/smtp"
|
|
)
|
|
|
|
type Mailer interface {
|
|
Send(to mail.Address, msg string) error
|
|
}
|
|
|
|
func NewEmail(from, host string, port int) (*Email, error) {
|
|
if _, err := mail.ParseAddress(from); err != nil {
|
|
return nil, fmt.Errorf("can't parse an email address for 'from': %v", err)
|
|
}
|
|
r := &Email{
|
|
host: host,
|
|
port: port,
|
|
from: from,
|
|
}
|
|
return r, nil
|
|
}
|
|
|
|
type Email struct {
|
|
host string
|
|
port int
|
|
from string
|
|
}
|
|
|
|
func (e Email) Send(to mail.Address, msg string) error {
|
|
c, err := smtp.Dial(fmt.Sprintf("%s:%d", e.host, e.port))
|
|
if err != nil {
|
|
return fmt.Errorf("couldn't dial mail server: %v", err)
|
|
}
|
|
defer c.Close()
|
|
if err := c.Mail(e.from); err != nil {
|
|
return err
|
|
}
|
|
if err := c.Rcpt(to.String()); err != nil {
|
|
return err
|
|
}
|
|
wc, err := c.Data()
|
|
if err != nil {
|
|
return fmt.Errorf("problem sending mail: %v", err)
|
|
}
|
|
buf := bytes.NewBufferString("Subject: your api key\n\n" + msg)
|
|
buf.WriteTo(wc)
|
|
if err := c.Quit(); err != nil {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|