-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailing.go
93 lines (77 loc) · 2.39 KB
/
mailing.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
package mails
import (
"context"
"fmt"
"io"
"os"
"strings"
"github.com/spacetab-io/configuration-structs-go/v2/errors"
"github.com/spacetab-io/configuration-structs-go/v2/mailing"
"github.com/spacetab-io/mails-go/contracts"
"github.com/spacetab-io/mails-go/providers"
)
type Mailing struct {
provider contracts.ProviderInterface
msgCfg mailing.MessagingConfigInterface
}
func NewMailing(providerCfg mailing.MailProviderConfigInterface, msgCfg mailing.MessagingConfigInterface) (Mailing, error) {
var (
provider contracts.ProviderInterface
err error
)
switch providerCfg.Name() {
case mailing.MailProviderLogs:
var w io.Writer
switch providerCfg.GetHostPort().GetHost() {
case "stdout":
w = os.Stdout
case "stderr":
w = os.Stderr
default:
w = os.Stdout
}
logger := NewLogger(w)
provider, err = providers.NewLogProvider(mailing.LogsConfig{}, logger)
case mailing.MailProviderFile:
provider, err = providers.NewFileProvider(providerCfg)
case mailing.MailProviderMailgun:
provider, err = providers.NewMailgun(providerCfg)
case mailing.MailProviderMandrill:
provider, err = providers.NewMandrill(providerCfg)
case mailing.MailProviderSendgrid:
provider, err = providers.NewSendgrid(providerCfg)
case mailing.MailProviderSMTP:
provider, err = providers.NewSMTP(providerCfg)
default:
return Mailing{}, errors.ErrUnknownProvider
}
if err != nil {
return Mailing{}, fmt.Errorf("provider init error: %w", err)
}
return Mailing{provider: provider, msgCfg: msgCfg}, nil
}
func NewMailingForProvider(provider contracts.ProviderInterface, msgCfg mailing.MessagingConfigInterface) Mailing {
return Mailing{provider: provider, msgCfg: msgCfg}
}
func (m Mailing) Send(ctx context.Context, msg contracts.MessageInterface) error {
if msg.GetMimeType().IsEmpty() && !m.msgCfg.GetMimeType().IsEmpty() {
msg.SetMimeType(m.msgCfg.GetMimeType())
}
if msg.GetFrom().IsEmpty() && !m.msgCfg.GetFrom().IsEmpty() {
_ = msg.SetFrom(m.msgCfg.GetFrom())
}
if !m.msgCfg.GetReplyTo().IsEmpty() && msg.GetReplyTo().IsEmpty() {
_ = msg.SetReplyTo(m.msgCfg.GetReplyTo())
}
if m.msgCfg.GetSubjectPrefix() != "" {
_ = msg.SetSubject(fmt.Sprintf(
"%s %s",
strings.TrimSpace(m.msgCfg.GetSubjectPrefix()),
strings.TrimSpace(msg.GetSubject()),
))
}
if err := m.provider.Send(ctx, msg); err != nil {
return fmt.Errorf("mailing send error: %w", err)
}
return nil
}