github.com/bitcubate/cryptojournal@v1.2.5-0.20171102134152-f578b3d788ab/src/lib/mail/mail.go (about)

     1  package mail
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  
     7  	"github.com/fragmenta/view"
     8  )
     9  
    10  // TODO - add more mail services, at present only sendgrid is supported
    11  // Usage:
    12  // email := mail.New(recipient)
    13  // email.Subject = "blah"
    14  // email.Body = blah
    15  // mail.Send(email,context)
    16  
    17  // Sender is the interface for our adapters for mail services.
    18  type Sender interface {
    19  	Send(email *Email) error
    20  }
    21  
    22  // Context defines a simple list of string:value pairs for mail templates.
    23  type Context map[string]interface{}
    24  
    25  // Production should be set to true in production environment.
    26  var Production = false
    27  
    28  // Service is the mail adapter to send with and should be set on startup.
    29  var Service Sender
    30  
    31  // Send the email using our default adapter and optional context.
    32  func Send(email *Email, context Context) error {
    33  	// If we have a template, render the email in that template
    34  	if email.Body == "" && email.Template != "" {
    35  		var err error
    36  		email.Body, err = RenderTemplate(email, context)
    37  		if err != nil {
    38  			return err
    39  		}
    40  	}
    41  
    42  	// If dev just log and return, don't send messages
    43  	if !Production {
    44  		fmt.Printf("#debug mail sent:%s\n", email)
    45  		return nil
    46  	}
    47  
    48  	return Service.Send(email)
    49  }
    50  
    51  // RenderTemplate renders the email into its template with context.
    52  func RenderTemplate(email *Email, context Context) (string, error) {
    53  	if email.Template == "" || context == nil {
    54  		return "", errors.New("mail: missing template or context")
    55  	}
    56  
    57  	view := view.NewWithPath("", nil)
    58  	view.Layout(email.Layout)
    59  	view.Template(email.Template)
    60  	view.Context(context)
    61  	body, err := view.RenderToStringWithLayout()
    62  	if err != nil {
    63  		return "", err
    64  	}
    65  
    66  	return body, nil
    67  }