1package mail_test
2
3import (
4	"bytes"
5	"io"
6	"log"
7	"testing"
8	"time"
9
10	"github.com/emersion/go-message/mail"
11)
12
13func ExampleWriter() {
14	var b bytes.Buffer
15
16	from := []*mail.Address{{"Mitsuha Miyamizu", "mitsuha.miyamizu@example.org"}}
17	to := []*mail.Address{{"Taki Tachibana", "taki.tachibana@example.org"}}
18
19	// Create our mail header
20	var h mail.Header
21	h.SetDate(time.Now())
22	h.SetAddressList("From", from)
23	h.SetAddressList("To", to)
24
25	// Create a new mail writer
26	mw, err := mail.CreateWriter(&b, h)
27	if err != nil {
28		log.Fatal(err)
29	}
30
31	// Create a text part
32	tw, err := mw.CreateInline()
33	if err != nil {
34		log.Fatal(err)
35	}
36	var th mail.InlineHeader
37	th.Set("Content-Type", "text/plain")
38	w, err := tw.CreatePart(th)
39	if err != nil {
40		log.Fatal(err)
41	}
42	io.WriteString(w, "Who are you?")
43	w.Close()
44	tw.Close()
45
46	// Create an attachment
47	var ah mail.AttachmentHeader
48	ah.Set("Content-Type", "image/jpeg")
49	ah.SetFilename("picture.jpg")
50	w, err = mw.CreateAttachment(ah)
51	if err != nil {
52		log.Fatal(err)
53	}
54	// TODO: write a JPEG file to w
55	w.Close()
56
57	mw.Close()
58
59	log.Println(b.String())
60}
61
62func TestWriter(t *testing.T) {
63	var b bytes.Buffer
64
65	var h mail.Header
66	h.SetSubject("Your Name")
67	mw, err := mail.CreateWriter(&b, h)
68	if err != nil {
69		t.Fatal(err)
70	}
71
72	// Create a text part
73	tw, err := mw.CreateInline()
74	if err != nil {
75		t.Fatal(err)
76	}
77	var th mail.InlineHeader
78	th.Set("Content-Type", "text/plain")
79	w, err := tw.CreatePart(th)
80	if err != nil {
81		t.Fatal(err)
82	}
83	io.WriteString(w, "Who are you?")
84	w.Close()
85	tw.Close()
86
87	// Create an attachment
88	var ah mail.AttachmentHeader
89	ah.Set("Content-Type", "text/plain")
90	ah.SetFilename("note.txt")
91	w, err = mw.CreateAttachment(ah)
92	if err != nil {
93		t.Fatal(err)
94	}
95	io.WriteString(w, "I'm Mitsuha.")
96	w.Close()
97
98	mw.Close()
99
100	testReader(t, &b)
101}
102
103func TestWriter_singleInline(t *testing.T) {
104	var b bytes.Buffer
105
106	var h mail.Header
107	h.SetSubject("Your Name")
108	mw, err := mail.CreateWriter(&b, h)
109	if err != nil {
110		t.Fatal(err)
111	}
112
113	// Create a text part
114	var th mail.InlineHeader
115	th.Set("Content-Type", "text/plain")
116	w, err := mw.CreateSingleInline(th)
117	if err != nil {
118		t.Fatal(err)
119	}
120	io.WriteString(w, "Who are you?")
121	w.Close()
122
123	// Create an attachment
124	var ah mail.AttachmentHeader
125	ah.Set("Content-Type", "text/plain")
126	ah.SetFilename("note.txt")
127	w, err = mw.CreateAttachment(ah)
128	if err != nil {
129		t.Fatal(err)
130	}
131	io.WriteString(w, "I'm Mitsuha.")
132	w.Close()
133
134	mw.Close()
135
136	t.Logf("Formatted message: \n%v", b.String())
137
138	testReader(t, &b)
139}
140