...

Source file src/github.com/go-mail/mail/example_test.go

Documentation: github.com/go-mail/mail

     1  package mail_test
     2  
     3  import (
     4  	"fmt"
     5  	"html/template"
     6  	"io"
     7  	"log"
     8  	"time"
     9  
    10  	"gopkg.in/mail.v2"
    11  )
    12  
    13  func Example() {
    14  	m := mail.NewMessage()
    15  	m.SetHeader("From", "alex@example.com")
    16  	m.SetHeader("To", "bob@example.com", "cora@example.com")
    17  	m.SetAddressHeader("Cc", "dan@example.com", "Dan")
    18  	m.SetHeader("Subject", "Hello!")
    19  	m.SetBody("text/html", "Hello <b>Bob</b> and <i>Cora</i>!")
    20  	m.Attach("/home/Alex/lolcat.jpg")
    21  
    22  	d := mail.NewDialer("smtp.example.com", 587, "user", "123456")
    23  	d.StartTLSPolicy = mail.MandatoryStartTLS
    24  
    25  	// Send the email to Bob, Cora and Dan.
    26  	if err := d.DialAndSend(m); err != nil {
    27  		panic(err)
    28  	}
    29  }
    30  
    31  // A daemon that listens to a channel and sends all incoming messages.
    32  func Example_daemon() {
    33  	ch := make(chan *mail.Message)
    34  
    35  	go func() {
    36  		d := mail.NewDialer("smtp.example.com", 587, "user", "123456")
    37  		d.StartTLSPolicy = mail.MandatoryStartTLS
    38  
    39  		var s mail.SendCloser
    40  		var err error
    41  		open := false
    42  		for {
    43  			select {
    44  			case m, ok := <-ch:
    45  				if !ok {
    46  					return
    47  				}
    48  				if !open {
    49  					if s, err = d.Dial(); err != nil {
    50  						panic(err)
    51  					}
    52  					open = true
    53  				}
    54  				if err := mail.Send(s, m); err != nil {
    55  					log.Print(err)
    56  				}
    57  			// Close the connection to the SMTP server if no email was sent in
    58  			// the last 30 seconds.
    59  			case <-time.After(30 * time.Second):
    60  				if open {
    61  					if err := s.Close(); err != nil {
    62  						panic(err)
    63  					}
    64  					open = false
    65  				}
    66  			}
    67  		}
    68  	}()
    69  
    70  	// Use the channel in your program to send emails.
    71  
    72  	// Close the channel to stop the mail daemon.
    73  	close(ch)
    74  }
    75  
    76  // Efficiently send a customized newsletter to a list of recipients.
    77  func Example_newsletter() {
    78  	// The list of recipients.
    79  	var list []struct {
    80  		Name    string
    81  		Address string
    82  	}
    83  
    84  	d := mail.NewDialer("smtp.example.com", 587, "user", "123456")
    85  	d.StartTLSPolicy = mail.MandatoryStartTLS
    86  	s, err := d.Dial()
    87  	if err != nil {
    88  		panic(err)
    89  	}
    90  
    91  	m := mail.NewMessage()
    92  	for _, r := range list {
    93  		m.SetHeader("From", "no-reply@example.com")
    94  		m.SetAddressHeader("To", r.Address, r.Name)
    95  		m.SetHeader("Subject", "Newsletter #1")
    96  		m.SetBody("text/html", fmt.Sprintf("Hello %s!", r.Name))
    97  
    98  		if err := mail.Send(s, m); err != nil {
    99  			log.Printf("Could not send email to %q: %v", r.Address, err)
   100  		}
   101  		m.Reset()
   102  	}
   103  }
   104  
   105  // Send an email using a local SMTP server.
   106  func Example_noAuth() {
   107  	m := mail.NewMessage()
   108  	m.SetHeader("From", "from@example.com")
   109  	m.SetHeader("To", "to@example.com")
   110  	m.SetHeader("Subject", "Hello!")
   111  	m.SetBody("text/plain", "Hello!")
   112  
   113  	d := mail.Dialer{Host: "localhost", Port: 587}
   114  	if err := d.DialAndSend(m); err != nil {
   115  		panic(err)
   116  	}
   117  }
   118  
   119  // Send an email using an API or postfix.
   120  func Example_noSMTP() {
   121  	m := mail.NewMessage()
   122  	m.SetHeader("From", "from@example.com")
   123  	m.SetHeader("To", "to@example.com")
   124  	m.SetHeader("Subject", "Hello!")
   125  	m.SetBody("text/plain", "Hello!")
   126  
   127  	s := mail.SendFunc(func(from string, to []string, msg io.WriterTo) error {
   128  		// Implements you email-sending function, for example by calling
   129  		// an API, or running postfix, etc.
   130  		fmt.Println("From:", from)
   131  		fmt.Println("To:", to)
   132  		return nil
   133  	})
   134  
   135  	if err := mail.Send(s, m); err != nil {
   136  		panic(err)
   137  	}
   138  	// Output:
   139  	// From: from@example.com
   140  	// To: [to@example.com]
   141  }
   142  
   143  var m *mail.Message
   144  
   145  func ExampleSetCopyFunc() {
   146  	m.Attach("foo.txt", mail.SetCopyFunc(func(w io.Writer) error {
   147  		_, err := w.Write([]byte("Content of foo.txt"))
   148  		return err
   149  	}))
   150  }
   151  
   152  func ExampleSetHeader() {
   153  	h := map[string][]string{"Content-ID": {"<foo@bar.mail>"}}
   154  	m.Attach("foo.jpg", mail.SetHeader(h))
   155  }
   156  
   157  func ExampleRename() {
   158  	m.Attach("/tmp/0000146.jpg", mail.Rename("picture.jpg"))
   159  }
   160  
   161  func ExampleMessage_AddAlternative() {
   162  	m.SetBody("text/plain", "Hello!")
   163  	m.AddAlternative("text/html", "<p>Hello!</p>")
   164  }
   165  
   166  func ExampleMessage_AddAlternativeWriter() {
   167  	t := template.Must(template.New("example").Parse("Hello {{.}}!"))
   168  	m.AddAlternativeWriter("text/plain", func(w io.Writer) error {
   169  		return t.Execute(w, "Bob")
   170  	})
   171  }
   172  
   173  func ExampleMessage_Attach() {
   174  	m.Attach("/tmp/image.jpg")
   175  }
   176  
   177  func ExampleMessage_Embed() {
   178  	m.Embed("/tmp/image.jpg")
   179  	m.SetBody("text/html", `<img src="cid:image.jpg" alt="My image" />`)
   180  }
   181  
   182  func ExampleMessage_FormatAddress() {
   183  	m.SetHeader("To", m.FormatAddress("bob@example.com", "Bob"), m.FormatAddress("cora@example.com", "Cora"))
   184  }
   185  
   186  func ExampleMessage_FormatDate() {
   187  	m.SetHeaders(map[string][]string{
   188  		"X-Date": {m.FormatDate(time.Now())},
   189  	})
   190  }
   191  
   192  func ExampleMessage_SetAddressHeader() {
   193  	m.SetAddressHeader("To", "bob@example.com", "Bob")
   194  }
   195  
   196  func ExampleMessage_SetBody() {
   197  	m.SetBody("text/plain", "Hello!")
   198  }
   199  
   200  func ExampleMessage_SetBodyWriter() {
   201  	t := template.Must(template.New("example").Parse("Hello {{.}}!"))
   202  	m.SetBodyWriter("text/plain", func(w io.Writer) error {
   203  		return t.Execute(w, "Bob")
   204  	})
   205  }
   206  
   207  func ExampleMessage_SetDateHeader() {
   208  	m.SetDateHeader("X-Date", time.Now())
   209  }
   210  
   211  func ExampleMessage_SetHeader() {
   212  	m.SetHeader("Subject", "Hello!")
   213  }
   214  
   215  func ExampleMessage_SetHeaders() {
   216  	m.SetHeaders(map[string][]string{
   217  		"From":    {m.FormatAddress("alex@example.com", "Alex")},
   218  		"To":      {"bob@example.com", "cora@example.com"},
   219  		"Subject": {"Hello"},
   220  	})
   221  }
   222  
   223  func ExampleSetCharset() {
   224  	m = mail.NewMessage(mail.SetCharset("ISO-8859-1"))
   225  }
   226  
   227  func ExampleSetEncoding() {
   228  	m = mail.NewMessage(mail.SetEncoding(mail.Base64))
   229  }
   230  
   231  func ExampleSetPartEncoding() {
   232  	m.SetBody("text/plain", "Hello!", mail.SetPartEncoding(mail.Unencoded))
   233  }
   234  

View as plain text