-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
msg.go
2957 lines (2775 loc) · 115 KB
/
msg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2022-2023 The go-mail Authors
//
// SPDX-License-Identifier: MIT
package mail
import (
"bytes"
"context"
"embed"
"errors"
"fmt"
ht "html/template"
"io"
"io/fs"
"mime"
"net/mail"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
tt "text/template"
"time"
)
var (
// ErrNoFromAddress indicates that the FROM address is not set, which is required.
ErrNoFromAddress = errors.New("no FROM address set")
// ErrNoRcptAddresses indicates that no recipient addresses have been set.
ErrNoRcptAddresses = errors.New("no recipient addresses set")
)
const (
// errTplExecuteFailed indicates that the execution of a template has failed, including the underlying error.
errTplExecuteFailed = "failed to execute template: %w"
// errTplPointerNil indicates that a template pointer is nil, which prevents further template execution or
// processing.
errTplPointerNil = "template pointer is nil"
// errParseMailAddr indicates that parsing of a mail address has failed, including the problematic address
// and error.
errParseMailAddr = "failed to parse mail address %q: %w"
)
const (
// NoPGP indicates that a message should not be treated as PGP encrypted or signed and is the default value
// for a message
NoPGP PGPType = iota
// PGPEncrypt indicates that a message should be treated as PGP encrypted. This works closely together with
// the corresponding go-mail-middleware.
PGPEncrypt
// PGPSignature indicates that a message should be treated as PGP signed. This works closely together with
// the corresponding go-mail-middleware.
PGPSignature
)
// MiddlewareType is a type wrapper for a string. It describes the type of the Middleware and needs to be
// returned by the Middleware.Type method to satisfy the Middleware interface.
type MiddlewareType string
// Middleware represents the interface for modifying or handling email messages. A Middleware allows the user to
// alter a Msg before it is finally processed. Multiple Middleware can be applied to a Msg.
//
// Type returns a unique MiddlewareType. It describes the type of Middleware and makes sure that
// a Middleware is only applied once.
// Handle performs all the processing to the Msg. It always needs to return a Msg back.
type Middleware interface {
Handle(*Msg) *Msg
Type() MiddlewareType
}
// PGPType is a type wrapper for an int, representing a type of PGP encryption or signature.
type PGPType int
// Msg represents an email message with various headers, attachments, and encoding settings.
//
// The Msg is the central part of go-mail. It provided a lot of methods that you would expect in a mail
// user agent (MUA). Msg satisfies the io.WriterTo and io.Reader interfaces.
type Msg struct {
// addrHeader holds a mapping between AddrHeader keys and their corresponding slices of mail.Address pointers.
addrHeader map[AddrHeader][]*mail.Address
// attachments holds a list of File pointers that represent files either as attachments or embeds files in
// a Msg.
attachments []*File
// boundary represents the delimiter for separating parts in a multipart message.
boundary string
// charset represents the Charset of the Msg.
//
// By default we set CharsetUTF8 for a Msg unless overridden by a corresponding MsgOption.
charset Charset
// embeds contains a slice of File pointers representing the embedded files in a Msg.
embeds []*File
// encoder is a mime.WordEncoder used to encode strings (such as email headers) using a specified
// Encoding.
encoder mime.WordEncoder
// encoding specifies the type of Encoding used for email messages and/or parts.
encoding Encoding
// genHeader is a map where the keys are email headers (of type Header) and the values are slices of strings
// representing header values.
genHeader map[Header][]string
// isDelivered indicates wether the Msg has been delivered.
isDelivered bool
// middlewares is a slice of Middleware used for modifying or handling messages before they are processed.
//
// middlewares are processed in FIFO order.
middlewares []Middleware
// mimever represents the MIME version used in a Msg.
mimever MIMEVersion
// parts is a slice that holds pointers to Part structures, which represent different parts of a Msg.
parts []*Part
// preformHeader maps Header types to their already preformatted string values.
//
// Preformatted Header values will not be affected by automatic line breaks.
preformHeader map[Header]string
// pgptype indicates that a message has a PGPType assigned and therefore will generate
// different Content-Type settings in the msgWriter.
pgptype PGPType
// sendError represents an error encountered during the process of sending a Msg during the
// Client.Send operation.
//
// sendError will hold an error of type SendError.
sendError error
// noDefaultUserAgent indicates whether the default User-Agent will be omitted for the Msg when it is
// being sent.
//
// This can be useful in scenarios where headers are conditionally passed based on receipt - i. e. SMTP proxies.
noDefaultUserAgent bool
}
// SendmailPath is the default system path to the sendmail binary - at least on standard Unix-like OS.
const SendmailPath = "/usr/sbin/sendmail"
// MsgOption is a function type that modifies a Msg instance during its creation or initialization.
type MsgOption func(*Msg)
// NewMsg creates a new email message with optional MsgOption functions that customize various aspects
// of the message.
//
// This function initializes a new Msg instance with default values for address headers, character set,
// encoding, general headers, and MIME version. It then applies any provided MsgOption functions to
// customize the message according to the user's needs. If an option is nil, it will be ignored.
// After applying the options, the function sets the appropriate MIME WordEncoder for the message.
//
// Parameters:
// - opts: A variadic list of MsgOption functions that can be used to customize the Msg instance.
//
// Returns:
// - A pointer to the newly created Msg instance.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5321
func NewMsg(opts ...MsgOption) *Msg {
msg := &Msg{
addrHeader: make(map[AddrHeader][]*mail.Address),
charset: CharsetUTF8,
encoding: EncodingQP,
genHeader: make(map[Header][]string),
preformHeader: make(map[Header]string),
mimever: MIME10,
}
// Override defaults with optionally provided MsgOption functions.
for _, option := range opts {
if option == nil {
continue
}
option(msg)
}
// Set the matcing mime.WordEncoder for the Msg
msg.setEncoder()
return msg
}
// WithCharset sets the Charset type for a Msg during its creation or initialization.
//
// This MsgOption function allows you to specify the character set to be used in the email message.
// The charset defines how the text in the message is encoded and interpreted by the email client.
// This option should be called when creating a new Msg instance to ensure that the desired charset
// is set correctly.
//
// Parameters:
// - charset: The Charset value that specifies the desired character set for the Msg.
//
// Returns:
// - A MsgOption function that can be used to customize the Msg instance.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc2047#section-5
func WithCharset(charset Charset) MsgOption {
return func(m *Msg) {
m.charset = charset
}
}
// WithEncoding sets the Encoding type for a Msg during its creation or initialization.
//
// This MsgOption function allows you to specify the encoding type to be used in the email message.
// The encoding defines how the message content is encoded, which affects how it is transmitted
// and decoded by email clients. This option should be called when creating a new Msg instance to
// ensure that the desired encoding is set correctly.
//
// Parameters:
// - encoding: The Encoding value that specifies the desired encoding type for the Msg.
//
// Returns:
// - A MsgOption function that can be used to customize the Msg instance.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc2047#section-6
func WithEncoding(encoding Encoding) MsgOption {
return func(m *Msg) {
m.encoding = encoding
}
}
// WithMIMEVersion sets the MIMEVersion type for a Msg during its creation or initialization.
//
// Note that in the context of email, MIME Version 1.0 is the only officially standardized and
// supported version. While MIME has been updated and extended over time via various RFCs, these
// updates and extensions do not introduce new MIME versions; they refine or add features within
// the framework of MIME 1.0. Therefore, there should be no reason to ever use this MsgOption.
//
// Parameters:
// - version: The MIMEVersion value that specifies the desired MIME version for the Msg.
//
// Returns:
// - A MsgOption function that can be used to customize the Msg instance.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc1521
// - https://datatracker.ietf.org/doc/html/rfc2045
// - https://datatracker.ietf.org/doc/html/rfc2049
func WithMIMEVersion(version MIMEVersion) MsgOption {
return func(m *Msg) {
m.mimever = version
}
}
// WithBoundary sets the boundary of a Msg to the provided string value during its creation or
// initialization.
//
// Note that by default, random MIME boundaries are created. This option should only be used if
// a specific boundary is required for the email message. Using a predefined boundary can be
// helpful when constructing multipart messages with specific formatting or content separation.
//
// Parameters:
// - boundary: The string value that specifies the desired boundary for the Msg.
//
// Returns:
// - A MsgOption function that can be used to customize the Msg instance.
func WithBoundary(boundary string) MsgOption {
return func(m *Msg) {
m.boundary = boundary
}
}
// WithMiddleware adds the given Middleware to the end of the list of the Client middlewares slice.
// Middleware are processed in FIFO order.
//
// This MsgOption function allows you to specify custom middleware that will be applied during the
// message handling process. Middleware can be used to modify the message, perform logging, or
// implement additional functionality as the message flows through the system. Each middleware
// is executed in the order it was added.
//
// Parameters:
// - middleware: The Middleware to be added to the list for processing.
//
// Returns:
// - A MsgOption function that can be used to customize the Msg instance.
func WithMiddleware(middleware Middleware) MsgOption {
return func(m *Msg) {
m.middlewares = append(m.middlewares, middleware)
}
}
// WithPGPType sets the PGP type for the Msg during its creation or initialization, determining
// the encryption or signature method.
//
// This MsgOption function allows you to specify the PGP (Pretty Good Privacy) type to be used
// for securing the message. The chosen PGP type influences how the message is encrypted or
// signed, ensuring confidentiality and integrity of the content. This option should be called
// when creating a new Msg instance to set the desired PGP type appropriately.
//
// Parameters:
// - pgptype: The PGPType value that specifies the desired PGP type for the Msg.
//
// Returns:
// - A MsgOption function that can be used to customize the Msg instance.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc4880
func WithPGPType(pgptype PGPType) MsgOption {
return func(m *Msg) {
m.pgptype = pgptype
}
}
// WithNoDefaultUserAgent disables the inclusion of a default User-Agent header in the Msg during
// its creation or initialization.
//
// This MsgOption function allows you to customize the Msg instance by omitting the default
// User-Agent header, which is typically included to provide information about the software
// sending the email. This option can be useful when you want to have more control over the
// headers included in the message, such as when sending from a custom application or for
// privacy reasons.
//
// Returns:
// - A MsgOption function that can be used to customize the Msg instance.
func WithNoDefaultUserAgent() MsgOption {
return func(m *Msg) {
m.noDefaultUserAgent = true
}
}
// SetCharset sets or overrides the currently set encoding charset of the Msg.
//
// This method allows you to specify a character set for the email message. The charset is
// important for ensuring that the content of the message is correctly interpreted by
// mail clients. Common charset values include UTF-8, ISO-8859-1, and others. If a charset
// is not explicitly set, CharsetUTF8 is used as default.
//
// Parameters:
// - charset: The Charset value to set for the Msg, determining the encoding used for the message content.
func (m *Msg) SetCharset(charset Charset) {
m.charset = charset
}
// SetEncoding sets or overrides the currently set Encoding of the Msg.
//
// This method allows you to specify the encoding type for the email message. The encoding
// determines how the message content is represented and can affect the size and compatibility
// of the email. Common encoding types include Base64 and Quoted-Printable. Setting a new
// encoding may also adjust how the message content is processed and transmitted.
//
// Parameters:
// - encoding: The Encoding value to set for the Msg, determining the method used to encode the
// message content.
func (m *Msg) SetEncoding(encoding Encoding) {
m.encoding = encoding
m.setEncoder()
}
// SetBoundary sets or overrides the currently set boundary of the Msg.
//
// This method allows you to specify a custom boundary string for the MIME message. The
// boundary is used to separate different parts of the message, especially when dealing
// with multipart messages. By default, the Msg generates random MIME boundaries. This
// function should only be used if you have a specific boundary requirement for the
// message. Ensure that the boundary value does not conflict with any content within the
// message to avoid parsing errors.
//
// Parameters:
// - boundary: The string value representing the boundary to set for the Msg, used in
// multipart messages to delimit different sections.
func (m *Msg) SetBoundary(boundary string) {
m.boundary = boundary
}
// SetMIMEVersion sets or overrides the currently set MIME version of the Msg.
//
// In the context of email, MIME Version 1.0 is the only officially standardized and
// supported version. Although MIME has been updated and extended over time through
// various RFCs, these updates do not introduce new MIME versions; they refine or add
// features within the framework of MIME 1.0. Therefore, there is generally no need to
// use this function to set a different MIME version.
//
// Parameters:
// - version: The MIMEVersion value to set for the Msg, which determines the MIME
// version used in the email message.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc1521
// - https://datatracker.ietf.org/doc/html/rfc2045
// - https://datatracker.ietf.org/doc/html/rfc2049
func (m *Msg) SetMIMEVersion(version MIMEVersion) {
m.mimever = version
}
// SetPGPType sets or overrides the currently set PGP type for the Msg, determining the
// encryption or signature method.
//
// This method allows you to specify the PGP type that will be used when encrypting or
// signing the message. Different PGP types correspond to various encryption and signing
// algorithms, and selecting the appropriate type is essential for ensuring the security
// and integrity of the message content.
//
// Parameters:
// - pgptype: The PGPType value to set for the Msg, which determines the encryption
// or signature method used for the email message.
func (m *Msg) SetPGPType(pgptype PGPType) {
m.pgptype = pgptype
}
// Encoding returns the currently set Encoding of the Msg as a string.
//
// This method retrieves the encoding type that is currently applied to the message. The
// encoding type determines how the message content is encoded for transmission. Common
// encoding types include quoted-printable and base64, and the returned string will reflect
// the specific encoding method in use.
//
// Returns:
// - A string representation of the current Encoding of the Msg.
func (m *Msg) Encoding() string {
return m.encoding.String()
}
// Charset returns the currently set Charset of the Msg as a string.
//
// This method retrieves the character set that is currently applied to the message. The
// charset defines the encoding for the text content of the message, ensuring that
// characters are displayed correctly across different email clients and platforms. The
// returned string will reflect the specific charset in use, such as UTF-8 or ISO-8859-1.
//
// Returns:
// - A string representation of the current Charset of the Msg.
func (m *Msg) Charset() string {
return m.charset.String()
}
// SetHeader sets a generic header field of the Msg.
//
// Deprecated: This method only exists for compatibility reasons. Please use SetGenHeader
// instead. For adding address headers like "To:" or "From", use SetAddrHeader instead.
//
// This method allows you to set a header field for the message, providing the header name
// and its corresponding values. However, it is recommended to utilize the newer methods
// for better clarity and functionality. Using SetGenHeader or SetAddrHeader is preferred
// for more specific header types, ensuring proper handling of the message headers.
//
// Parameters:
// - header: The header field to set in the Msg.
// - values: One or more string values to associate with the header field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3
// - https://datatracker.ietf.org/doc/html/rfc2047
func (m *Msg) SetHeader(header Header, values ...string) {
m.SetGenHeader(header, values...)
}
// SetGenHeader sets a generic header field of the Msg to the provided list of values.
//
// This method is intended for setting generic headers in the email message. It takes a
// header name and a variadic list of string values, encoding them as necessary before
// storing them in the message's internal header map.
//
// Note: For adding email address-related headers (like "To:", "From", "Cc", etc.),
// use SetAddrHeader instead to ensure proper formatting and validation.
//
// Parameters:
// - header: The header field to set in the Msg.
// - values: One or more string values to associate with the header field.
//
// This method ensures that all values are appropriately encoded for email transmission,
// adhering to the necessary standards.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3
// - https://datatracker.ietf.org/doc/html/rfc2047
func (m *Msg) SetGenHeader(header Header, values ...string) {
if m.genHeader == nil {
m.genHeader = make(map[Header][]string)
}
for i, val := range values {
values[i] = m.encodeString(val)
}
m.genHeader[header] = values
}
// SetHeaderPreformatted sets a generic header field of the Msg, which content is already preformatted.
//
// Deprecated: This method only exists for compatibility reasons. Please use
// SetGenHeaderPreformatted instead for setting preformatted generic header fields.
//
// Parameters:
// - header: The header field to set in the Msg.
// - value: The preformatted string value to associate with the header field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3
// - https://datatracker.ietf.org/doc/html/rfc2047
func (m *Msg) SetHeaderPreformatted(header Header, value string) {
m.SetGenHeaderPreformatted(header, value)
}
// SetGenHeaderPreformatted sets a generic header field of the Msg which content is already preformatted.
//
// This method does not take a slice of values but only a single value. The reason for this is that we do not
// perform any content alteration on these kinds of headers and expect the user to have already taken care of
// any kind of formatting required for the header.
//
// Note: This method should be used only as a last resort. Since the user is responsible for the formatting of
// the message header, we cannot guarantee any compliance with RFC 2822. It is advised to use SetGenHeader
// instead for general header fields.
//
// Parameters:
// - header: The header field to set in the Msg.
// - value: The preformatted string value to associate with the header field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc2822
func (m *Msg) SetGenHeaderPreformatted(header Header, value string) {
if m.preformHeader == nil {
m.preformHeader = make(map[Header]string)
}
m.preformHeader[header] = value
}
// SetAddrHeader sets the specified AddrHeader for the Msg to the given values.
//
// Addresses are parsed according to RFC 5322. If parsing any of the provided values fails,
// an error is returned. If you cannot guarantee that all provided values are valid, you can
// use SetAddrHeaderIgnoreInvalid instead, which will silently skip any parsing errors.
//
// This method allows you to set address-related headers for the message, ensuring that the
// provided addresses are properly formatted and parsed. Using this method helps maintain the
// integrity of the email addresses within the message.
//
// Parameters:
// - header: The AddrHeader to set in the Msg (e.g., "From", "To", "Cc", "Bcc").
// - values: One or more string values representing the email addresses to associate with
// the specified header.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.4
func (m *Msg) SetAddrHeader(header AddrHeader, values ...string) error {
if m.addrHeader == nil {
m.addrHeader = make(map[AddrHeader][]*mail.Address)
}
var addresses []*mail.Address
for _, addrVal := range values {
address, err := mail.ParseAddress(addrVal)
if err != nil {
return fmt.Errorf(errParseMailAddr, addrVal, err)
}
addresses = append(addresses, address)
}
switch header {
case HeaderFrom:
if len(addresses) > 0 {
m.addrHeader[header] = []*mail.Address{addresses[0]}
}
default:
m.addrHeader[header] = addresses
}
return nil
}
// SetAddrHeaderIgnoreInvalid sets the specified AddrHeader for the Msg to the given values.
//
// Addresses are parsed according to RFC 5322. If parsing of any of the provided values fails,
// the error is ignored and the address is omitted from the address list.
//
// This method allows for setting address headers while ignoring invalid addresses. It is useful
// in scenarios where you want to ensure that only valid addresses are included without halting
// execution due to parsing errors.
//
// Parameters:
// - header: The AddrHeader field to set in the Msg.
// - values: One or more string values representing email addresses.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.4
func (m *Msg) SetAddrHeaderIgnoreInvalid(header AddrHeader, values ...string) {
if m.addrHeader == nil {
m.addrHeader = make(map[AddrHeader][]*mail.Address)
}
var addresses []*mail.Address
for _, addrVal := range values {
address, err := mail.ParseAddress(m.encodeString(addrVal))
if err != nil {
continue
}
addresses = append(addresses, address)
}
switch header {
case HeaderFrom:
if len(addresses) > 0 {
m.addrHeader[header] = []*mail.Address{addresses[0]}
}
default:
m.addrHeader[header] = addresses
}
}
// EnvelopeFrom sets the envelope from address for the Msg.
//
// The HeaderEnvelopeFrom address is generally not included in the mail body but only used by the
// Client for communication with the SMTP server. If the Msg has no "FROM" address set in the
// mail body, the msgWriter will try to use the envelope from address if it has been set for the Msg.
// The provided address is validated according to RFC 5322 and will return an error if the validation fails.
//
// Parameters:
// - from: The envelope from address to set in the Msg.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.4
func (m *Msg) EnvelopeFrom(from string) error {
return m.SetAddrHeader(HeaderEnvelopeFrom, from)
}
// EnvelopeFromFormat sets the provided name and mail address as HeaderEnvelopeFrom for the Msg.
//
// The HeaderEnvelopeFrom address is generally not included in the mail body but only used by the
// Client for communication with the SMTP server. If the Msg has no "FROM" address set in the mail
// body, the msgWriter will try to use the envelope from address if it has been set for the Msg.
// The provided name and address are validated according to RFC 5322 and will return an error if
// the validation fails.
//
// Parameters:
// - name: The name to associate with the envelope from address.
// - addr: The mail address to set as the envelope from address.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.4
func (m *Msg) EnvelopeFromFormat(name, addr string) error {
return m.SetAddrHeader(HeaderEnvelopeFrom, fmt.Sprintf(`"%s" <%s>`, name, addr))
}
// From sets the "FROM" address in the mail body for the Msg.
//
// The "FROM" address is included in the mail body and indicates the sender of the message to
// the recipient. This address is visible in the email client and is typically displayed to the
// recipient. If the "FROM" address is not set, the msgWriter may attempt to use the envelope
// from address (if available) for sending. The provided address is validated according to RFC
// 5322 and will return an error if the validation fails.
//
// Parameters:
// - from: The "FROM" address to set in the mail body.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.2
func (m *Msg) From(from string) error {
return m.SetAddrHeader(HeaderFrom, from)
}
// FromFormat sets the provided name and mail address as the "FROM" address in the mail body for the Msg.
//
// The "FROM" address is included in the mail body and indicates the sender of the message to
// the recipient, and is visible in the email client. If the "FROM" address is not explicitly
// set, the msgWriter may use the envelope from address (if provided) when sending the message.
// The provided name and address are validated according to RFC 5322 and will return an error
// if the validation fails.
//
// Parameters:
// - name: The name of the sender to include in the "FROM" address.
// - addr: The email address of the sender to include in the "FROM" address.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.2
func (m *Msg) FromFormat(name, addr string) error {
return m.SetAddrHeader(HeaderFrom, fmt.Sprintf(`"%s" <%s>`, name, addr))
}
// To sets one or more "TO" addresses in the mail body for the Msg.
//
// The "TO" address specifies the primary recipient(s) of the message and is included in the mail body.
// This address is visible to the recipient and any other recipients of the message. Multiple "TO" addresses
// can be set by passing them as variadic arguments to this method. Each provided address is validated
// according to RFC 5322, and an error will be returned if ANY validation fails.
//
// Parameters:
// - rcpts: One or more recipient email addresses to include in the "TO" field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) To(rcpts ...string) error {
return m.SetAddrHeader(HeaderTo, rcpts...)
}
// AddTo adds a single "TO" address to the existing list of recipients in the mail body for the Msg.
//
// This method allows you to add a single recipient to the "TO" field without replacing any previously set
// "TO" addresses. The "TO" address specifies the primary recipient(s) of the message and is visible in the mail
// client. The provided address is validated according to RFC 5322, and an error will be returned if the
// validation fails.
//
// Parameters:
// - rcpt: The recipient email address to add to the "TO" field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) AddTo(rcpt string) error {
return m.addAddr(HeaderTo, rcpt)
}
// AddToFormat adds a single "TO" address with the provided name and email to the existing list of recipients
// in the mail body for the Msg.
//
// This method allows you to add a recipient's name and email address to the "TO" field without replacing any
// previously set "TO" addresses. The "TO" address specifies the primary recipient(s) of the message and is
// visible in the mail client. The provided name and address are validated according to RFC 5322, and an error
// will be returned if the validation fails.
//
// Parameters:
// - name: The name of the recipient to add to the "TO" field.
// - addr: The email address of the recipient to add to the "TO" field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) AddToFormat(name, addr string) error {
return m.addAddr(HeaderTo, fmt.Sprintf(`"%s" <%s>`, name, addr))
}
// ToIgnoreInvalid sets one or more "TO" addresses in the mail body for the Msg, ignoring any invalid addresses.
//
// This method allows you to add multiple "TO" recipients to the message body. Unlike the standard `To` method,
// any invalid addresses are ignored, and no error is returned for those addresses. Valid addresses will still be
// included in the "TO" field, which is visible in the recipient's mail client. Use this method with caution if
// address validation is critical. Invalid addresses are determined according to RFC 5322.
//
// Parameters:
// - rcpts: One or more recipient addresses to add to the "TO" field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) ToIgnoreInvalid(rcpts ...string) {
m.SetAddrHeaderIgnoreInvalid(HeaderTo, rcpts...)
}
// ToFromString takes a string of comma-separated email addresses, validates each, and sets them as the
// "TO" addresses for the Msg.
//
// This method allows you to pass a single string containing multiple email addresses separated by commas.
// Each address is validated according to RFC 5322 and set as a recipient in the "TO" field. If any validation
// fails, an error will be returned. The addresses are visible in the mail body and displayed to recipients in
// the mail client. Any "TO" address applied previously will be overwritten.
//
// Parameters:
// - rcpts: A string containing multiple recipient addresses separated by commas.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) ToFromString(rcpts string) error {
src := strings.Split(rcpts, ",")
var dst []string
for _, address := range src {
address = strings.TrimSpace(address)
if address == "" {
continue
}
dst = append(dst, address)
}
return m.To(dst...)
}
// Cc sets one or more "CC" (carbon copy) addresses in the mail body for the Msg.
//
// The "CC" address specifies secondary recipient(s) of the message, and is included in the mail body.
// These addresses are visible to all recipients, including those listed in the "TO" and other "CC" fields.
// Multiple "CC" addresses can be set by passing them as variadic arguments to this method. Each provided
// address is validated according to RFC 5322, and an error will be returned if ANY validation fails.
//
// Parameters:
// - rcpts: One or more recipient addresses to be included in the "CC" field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) Cc(rcpts ...string) error {
return m.SetAddrHeader(HeaderCc, rcpts...)
}
// AddCc adds a single "CC" (carbon copy) address to the existing list of "CC" recipients in the mail body
// for the Msg.
//
// This method allows you to add a single recipient to the "CC" field without replacing any previously set "CC"
// addresses. The "CC" address specifies secondary recipient(s) and is visible to all recipients, including those
// in the "TO" field. The provided address is validated according to RFC 5322, and an error will be returned if
// the validation fails.
//
// Parameters:
// - rcpt: The recipient address to be added to the "CC" field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) AddCc(rcpt string) error {
return m.addAddr(HeaderCc, rcpt)
}
// AddCcFormat adds a single "CC" (carbon copy) address with the provided name and email to the existing list
// of "CC" recipients in the mail body for the Msg.
//
// This method allows you to add a recipient's name and email address to the "CC" field without replacing any
// previously set "CC" addresses. The "CC" address specifies secondary recipient(s) and is visible to all
// recipients, including those in the "TO" field. The provided name and address are validated according to
// RFC 5322, and an error will be returned if the validation fails.
//
// Parameters:
// - name: The name of the recipient to be added to the "CC" field.
// - addr: The email address of the recipient to be added to the "CC" field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) AddCcFormat(name, addr string) error {
return m.addAddr(HeaderCc, fmt.Sprintf(`"%s" <%s>`, name, addr))
}
// CcIgnoreInvalid sets one or more "CC" (carbon copy) addresses in the mail body for the Msg, ignoring any
// invalid addresses.
//
// This method allows you to add multiple "CC" recipients to the message body. Unlike the standard `Cc` method,
// any invalid addresses are ignored, and no error is returned for those addresses. Valid addresses will still
// be included in the "CC" field, which is visible to all recipients in the mail client. Use this method with
// caution if address validation is critical, as invalid addresses are determined according to RFC 5322.
//
// Parameters:
// - rcpts: One or more recipient email addresses to be added to the "CC" field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) CcIgnoreInvalid(rcpts ...string) {
m.SetAddrHeaderIgnoreInvalid(HeaderCc, rcpts...)
}
// CcFromString takes a string of comma-separated email addresses, validates each, and sets them as the "CC"
// addresses for the Msg.
//
// This method allows you to pass a single string containing multiple email addresses separated by commas.
// Each address is validated according to RFC 5322 and set as a recipient in the "CC" field. If any validation
// fails, an error will be returned. The addresses are visible in the mail body and displayed to recipients
// in the mail client.
//
// Parameters:
// - rcpts: A string containing multiple email addresses separated by commas.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) CcFromString(rcpts string) error {
src := strings.Split(rcpts, ",")
var dst []string
for _, address := range src {
address = strings.TrimSpace(address)
if address == "" {
continue
}
dst = append(dst, address)
}
return m.Cc(dst...)
}
// Bcc sets one or more "BCC" (blind carbon copy) addresses in the mail body for the Msg.
//
// The "BCC" address specifies recipient(s) of the message who will receive a copy without other recipients
// being aware of it. These addresses are not visible in the mail body or to any other recipients, ensuring
// the privacy of BCC'd recipients. Multiple "BCC" addresses can be set by passing them as variadic arguments
// to this method. Each provided address is validated according to RFC 5322, and an error will be returned
// if ANY validation fails.
//
// Parameters:
// - rcpts: One or more string values representing the BCC addresses to set in the Msg.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) Bcc(rcpts ...string) error {
return m.SetAddrHeader(HeaderBcc, rcpts...)
}
// AddBcc adds a single "BCC" (blind carbon copy) address to the existing list of "BCC" recipients in the mail
// body for the Msg.
//
// This method allows you to add a single recipient to the "BCC" field without replacing any previously set
// "BCC" addresses. The "BCC" address specifies recipient(s) of the message who will receive a copy without other
// recipients being aware of it. The provided address is validated according to RFC 5322, and an error will be
// returned if the validation fails.
//
// Parameters:
// - rcpt: The BCC address to add to the existing list of recipients in the Msg.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) AddBcc(rcpt string) error {
return m.addAddr(HeaderBcc, rcpt)
}
// AddBccFormat adds a single "BCC" (blind carbon copy) address with the provided name and email to the existing
// list of "BCC" recipients in the mail body for the Msg.
//
// This method allows you to add a recipient's name and email address to the "BCC" field without replacing
// any previously set "BCC" addresses. The "BCC" address specifies recipient(s) of the message who will receive
// a copy without other recipients being aware of it. The provided name and address are validated according to
// RFC 5322, and an error will be returned if the validation fails.
//
// Parameters:
// - name: The name of the recipient to add to the BCC field.
// - addr: The email address of the recipient to add to the BCC field.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) AddBccFormat(name, addr string) error {
return m.addAddr(HeaderBcc, fmt.Sprintf(`"%s" <%s>`, name, addr))
}
// BccIgnoreInvalid sets one or more "BCC" (blind carbon copy) addresses in the mail body for the Msg,
// ignoring any invalid addresses.
//
// This method allows you to add multiple "BCC" recipients to the message body. Unlike the standard `Bcc`
// method, any invalid addresses are ignored, and no error is returned for those addresses. Valid addresses
// will still be included in the "BCC" field, which ensures the privacy of the BCC'd recipients. Use this method
// with caution if address validation is critical, as invalid addresses are determined according to RFC 5322.
//
// Parameters:
// - rcpts: One or more string values representing the BCC email addresses to set.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) BccIgnoreInvalid(rcpts ...string) {
m.SetAddrHeaderIgnoreInvalid(HeaderBcc, rcpts...)
}
// BccFromString takes a string of comma-separated email addresses, validates each, and sets them as the "BCC"
// addresses for the Msg.
//
// This method allows you to pass a single string containing multiple email addresses separated by commas.
// Each address is validated according to RFC 5322 and set as a recipient in the "BCC" field. If any validation
// fails, an error will be returned. The addresses are not visible in the mail body and ensure the privacy of
// BCC'd recipients.
//
// Parameters:
// - rcpts: A string of comma-separated email addresses to set as BCC recipients.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.3
func (m *Msg) BccFromString(rcpts string) error {
src := strings.Split(rcpts, ",")
var dst []string
for _, address := range src {
address = strings.TrimSpace(address)
if address == "" {
continue
}
dst = append(dst, address)
}
return m.Bcc(dst...)
}
// ReplyTo sets the "Reply-To" address for the Msg, specifying where replies should be sent.
//
// This method takes a single email address as input and attempts to parse it. If the address is valid, it sets
// the "Reply-To" header in the message. The "Reply-To" address can be different from the "From" address,
// allowing the sender to specify an alternate address for responses. If the provided address cannot be parsed,
// an error will be returned, indicating the parsing failure.
//
// Parameters:
// - addr: The email address to set as the "Reply-To" address.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.2
func (m *Msg) ReplyTo(addr string) error {
replyTo, err := mail.ParseAddress(addr)
if err != nil {
return fmt.Errorf("failed to parse reply-to address: %w", err)
}
m.SetGenHeader(HeaderReplyTo, replyTo.String())
return nil
}
// ReplyToFormat sets the "Reply-To" address for the Msg using the provided name and email address, specifying
// where replies should be sent.
//
// This method formats the name and email address into a single "Reply-To" header. If the formatted address is valid,
// it sets the "Reply-To" header in the message. This allows the sender to specify a display name along with the
// reply address, providing clarity for recipients. If the constructed address cannot be parsed, an error will
// be returned, indicating the parsing failure.
//
// Parameters:
// - name: The display name associated with the reply address.
// - addr: The email address to set as the "Reply-To" address.
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.2
func (m *Msg) ReplyToFormat(name, addr string) error {
return m.ReplyTo(fmt.Sprintf(`"%s" <%s>`, name, addr))
}
// Subject sets the "Subject" header for the Msg, specifying the topic of the message.
//
// This method takes a single string as input and sets it as the "Subject" of the email. The subject line provides
// a brief summary of the content of the message, allowing recipients to quickly understand its purpose.