github.com/jackgris/buffalo@v0.10.3-0.20171206174715-b1dbfd2402de/mail/smtp_sender.go (about)

     1  package mail
     2  
     3  import (
     4  	"io"
     5  	"strconv"
     6  
     7  	"github.com/pkg/errors"
     8  	gomail "gopkg.in/gomail.v2"
     9  )
    10  
    11  //SMTPSender allows to send Emails by connecting to a SMTP server.
    12  type SMTPSender struct {
    13  	Dialer *gomail.Dialer
    14  }
    15  
    16  //Send a message using SMTP configuration or returns an error if something goes wrong.
    17  func (sm SMTPSender) Send(message Message) error {
    18  	m := gomail.NewMessage()
    19  
    20  	m.SetHeader("From", message.From)
    21  	m.SetHeader("To", message.To...)
    22  	m.SetHeader("Subject", message.Subject)
    23  	m.SetHeader("Cc", message.CC...)
    24  	m.SetHeader("Bcc", message.Bcc...)
    25  
    26  	if len(message.Bodies) > 0 {
    27  		mainBody := message.Bodies[0]
    28  		m.SetBody(mainBody.ContentType, mainBody.Content, gomail.SetPartEncoding(gomail.Unencoded))
    29  	}
    30  
    31  	if len(message.Bodies) > 1 {
    32  		for i := 1; i < len(message.Bodies); i++ {
    33  			alt := message.Bodies[i]
    34  			m.AddAlternative(alt.ContentType, alt.Content, gomail.SetPartEncoding(gomail.Unencoded))
    35  		}
    36  	}
    37  
    38  	for _, at := range message.Attachments {
    39  		settings := gomail.SetCopyFunc(func(w io.Writer) error {
    40  			if _, err := io.Copy(w, at.Reader); err != nil {
    41  				return err
    42  			}
    43  
    44  			return nil
    45  		})
    46  
    47  		m.Attach(at.Name, settings)
    48  	}
    49  
    50  	for field, value := range message.Headers {
    51  		m.SetHeader(field, value)
    52  	}
    53  
    54  	err := sm.Dialer.DialAndSend(m)
    55  
    56  	if err != nil {
    57  		return errors.WithStack(err)
    58  	}
    59  
    60  	return nil
    61  }
    62  
    63  //NewSMTPSender builds a SMTP mail based in passed config.
    64  func NewSMTPSender(host string, port string, user string, password string) (SMTPSender, error) {
    65  	iport, err := strconv.Atoi(port)
    66  
    67  	if err != nil {
    68  		return SMTPSender{}, errors.New("invalid port for the SMTP mail")
    69  	}
    70  
    71  	dialer := &gomail.Dialer{
    72  		Host: host,
    73  		Port: iport,
    74  	}
    75  
    76  	if user != "" {
    77  		dialer.Username = user
    78  		dialer.Password = password
    79  	}
    80  
    81  	return SMTPSender{
    82  		Dialer: dialer,
    83  	}, nil
    84  }