github.com/fedir/buffalo@v0.11.1/mail/message.go (about)

     1  package mail
     2  
     3  import (
     4  	"io"
     5  
     6  	"bytes"
     7  
     8  	"github.com/gobuffalo/buffalo/render"
     9  )
    10  
    11  //Message represents an Email message
    12  type Message struct {
    13  	From    string
    14  	To      []string
    15  	CC      []string
    16  	Bcc     []string
    17  	Subject string
    18  	Headers map[string]string
    19  
    20  	Bodies      []Body
    21  	Attachments []Attachment
    22  }
    23  
    24  // Body represents one of the bodies in the Message could be main or alternative
    25  type Body struct {
    26  	Content     string
    27  	ContentType string
    28  }
    29  
    30  // Attachment are files added into a email message
    31  type Attachment struct {
    32  	Name        string
    33  	Reader      io.Reader
    34  	ContentType string
    35  }
    36  
    37  // AddBody the message by receiving a renderer and rendering data, first message will be
    38  // used as the main message Body rest of them will be passed as alternative bodies on the
    39  // email message
    40  func (m *Message) AddBody(r render.Renderer, data render.Data) error {
    41  	buf := bytes.NewBuffer([]byte{})
    42  	err := r.Render(buf, data)
    43  
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	m.Bodies = append(m.Bodies, Body{
    49  		Content:     string(buf.Bytes()),
    50  		ContentType: r.ContentType(),
    51  	})
    52  
    53  	return nil
    54  }
    55  
    56  // AddBodies Allows to add multiple bodies to the message, it returns errors that
    57  // could happen in the rendering.
    58  func (m *Message) AddBodies(data render.Data, renderers ...render.Renderer) error {
    59  	for _, r := range renderers {
    60  		err := m.AddBody(r, data)
    61  		if err != nil {
    62  			return err
    63  		}
    64  	}
    65  
    66  	return nil
    67  }
    68  
    69  //AddAttachment adds the attachment to the list of attachments the Message has.
    70  func (m *Message) AddAttachment(name, contentType string, r io.Reader) error {
    71  	m.Attachments = append(m.Attachments, Attachment{
    72  		Name:        name,
    73  		ContentType: contentType,
    74  		Reader:      r,
    75  	})
    76  
    77  	return nil
    78  }
    79  
    80  // SetHeader sets the heder field and value for the message
    81  func (m *Message) SetHeader(field, value string) {
    82  	m.Headers[field] = value
    83  }
    84  
    85  //NewMessage Builds a new message.
    86  func NewMessage() Message {
    87  	return Message{Headers: map[string]string{}}
    88  }