Debian Codegraph @

mime.go

raw
1 package mailyak
2
3 import (
4 "bytes"
5 "crypto/rand"
6 "encoding/hex"
7 "fmt"
8 "io"
9 "mime/multipart"
10 "mime/quotedprintable"
11 "net/textproto"
12 "strings"
13 )
14
15 func (m *MailYak) buildMime(w io.Writer) error {
16 mb, err := randomBoundary()
17 if err != nil {
18 return err
19 }
20
21 ab, err := randomBoundary()
22 if err != nil {
23 return err
24 }
25
26 return m.buildMimeWithBoundaries(w, mb, ab)
27 }
28
29 // randomBoundary returns a random hexadecimal string used for separating MIME
30 // parts.
31 //
32 // The returned string must be sufficiently random to prevent malicious users
33 // from performing content injection attacks.
34 func randomBoundary() (string, error) {
35 buf := make([]byte, 30)
36 _, err := io.ReadFull(rand.Reader, buf)
37 if err != nil {
38 return "", err
39 }
40 return hex.EncodeToString(buf), nil
41 }
42
43 // buildMimeWithBoundaries creates the MIME message using mb and ab as MIME
44 // boundaries, and returns the generated MIME data as a buffer.
45 func (m *MailYak) buildMimeWithBoundaries(w io.Writer, mb, ab string) error {
46 if err := m.writeHeaders(w); err != nil {
47 return err
48 }
49
50 var (
51 hasBody = m.html.Len() != 0 || m.plain.Len() != 0
52 hasAttachments = len(m.attachments) != 0
53 )
54
55 // if we don't have text/html body or attachments we can skip Content-Type header
56 // in that case next default will be assumed
57 // Content-type: text/plain; charset=us-ascii
58 // See https://datatracker.ietf.org/doc/html/rfc2045#page-14
59 if !hasBody && !hasAttachments {
60 // The RFC said that body can be ommited: https://datatracker.ietf.org/doc/html/rfc822#section-3.1
61 // but for example mailhog can't correctly read message without any body.
62 // This CRLF just separate header section.
63 _, err := fmt.Fprint(w, "\r\n")
64 return err
65 }
66 // Start our multipart/mixed part
67 mixed := multipart.NewWriter(w)
68 if err := mixed.SetBoundary(mb); err != nil {
69 return err
70 }
71
72 // To avoid deferring a mixed.Close(), run the write in a closure and
73 // close the mixed after.
74 tryWrite := func() error {
75 fmt.Fprintf(w, "Content-Type: multipart/mixed;\r\n\tboundary=\"%s\"; charset=UTF-8\r\n\r\n", mixed.Boundary())
76
77 if hasBody {
78 if err := m.writeAlternativePart(mixed, ab); err != nil {
79 return err
80 }
81 }
82 if hasAttachments {
83 if err := m.writeAttachments(mixed, lineSplitterBuilder{}); err != nil {
84 return err
85 }
86 }
87 return nil
88 }
89
90 if err := tryWrite(); err != nil {
91 return err
92 }
93
94 return mixed.Close()
95 }
96
97 // writeHeaders writes the MIME-Version, Date, Reply-To, From, To and Subject headers,
98 // plus any custom headers set via AddHeader().
99 func (m *MailYak) writeHeaders(w io.Writer) error {
100 if _, err := w.Write([]byte(m.fromHeader())); err != nil {
101 return err
102 }
103
104 if _, err := w.Write([]byte("MIME-Version: 1.0\r\n")); err != nil {
105 return err
106 }
107
108 fmt.Fprintf(w, "Date: %s\r\n", m.date)
109
110 if m.replyTo != "" {
111 fmt.Fprintf(w, "Reply-To: %s\r\n", m.replyTo)
112 }
113
114 fmt.Fprintf(w, "Subject: %s\r\n", m.subject)
115
116 if len(m.toAddrs) > 0 {
117 commaSeparatedToAddrs := strings.Join(m.toAddrs, ",")
118 fmt.Fprintf(w, "To: %s\r\n", commaSeparatedToAddrs)
119 }
120
121 if len(m.ccAddrs) > 0 {
122 commaSeparatedCCAddrs := strings.Join(m.ccAddrs, ",")
123 fmt.Fprintf(w, "CC: %s\r\n", commaSeparatedCCAddrs)
124 }
125
126 if m.writeBccHeader && len(m.bccAddrs) > 0 {
127 commaSeparatedBCCAddrs := strings.Join(m.bccAddrs, ",")
128 fmt.Fprintf(w, "BCC: %s\r\n", commaSeparatedBCCAddrs)
129 }
130
131 for k, values := range m.headers {
132 for _, v := range values {
133 fmt.Fprintf(w, "%s: %s\r\n", k, v)
134 }
135 }
136
137 return nil
138 }
139
140 // fromHeader returns a correctly formatted From header, optionally with a name
141 // component.
142 func (m *MailYak) fromHeader() string {
143 if m.fromName == "" {
144 return fmt.Sprintf("From: %s\r\n", m.fromAddr)
145 }
146
147 return fmt.Sprintf("From: %s <%s>\r\n", m.fromName, m.fromAddr)
148 }
149
150 func (m *MailYak) writeAlternativePart(mixed *multipart.Writer, boundary string) error {
151 ctype := fmt.Sprintf("multipart/alternative;\r\n\tboundary=\"%s\"", boundary)
152
153 altPart, err := mixed.CreatePart(textproto.MIMEHeader{"Content-Type": {ctype}})
154 if err != nil {
155 return err
156 }
157
158 return m.writeBody(altPart, boundary)
159 }
160
161 // writeBody writes the text/plain and text/html mime parts.
162 // It's incorrect to call writeBody without html or plain content.
163 func (m *MailYak) writeBody(w io.Writer, boundary string) error {
164 alt := multipart.NewWriter(w)
165
166 if err := alt.SetBoundary(boundary); err != nil {
167 return err
168 }
169
170 var err error
171 writePart := func(ctype string, data []byte) {
172 if len(data) == 0 || err != nil {
173 return
174 }
175
176 c := fmt.Sprintf("%s; charset=UTF-8", ctype)
177
178 var part io.Writer
179 part, err = alt.CreatePart(textproto.MIMEHeader{"Content-Type": {c}, "Content-Transfer-Encoding": {"quoted-printable"}})
180 if err != nil {
181 return
182 }
183
184 var buf bytes.Buffer
185 qpw := quotedprintable.NewWriter(&buf)
186 _, _ = qpw.Write(data)
187 _ = qpw.Close()
188
189 _, err = part.Write(buf.Bytes())
190 }
191
192 writePart("text/plain", m.plain.Bytes())
193 writePart("text/html", m.html.Bytes())
194
195 // If closing the alt fails, and there's not already an error set, return the
196 // close error.
197 if closeErr := alt.Close(); err == nil && closeErr != nil {
198 return closeErr
199 }
200
201 return err
202 }