-
Notifications
You must be signed in to change notification settings - Fork 0
/
email_send.go
executable file
·76 lines (63 loc) · 1.89 KB
/
email_send.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
package campid
import (
"context"
"fmt"
"net/smtp"
"github.com/influx6/npkg/nerror"
"github.com/influx6/npkg/ntrace"
openTracing "github.com/opentracing/opentracing-go"
)
var _ MailCode = (*SMTPMailCode)(nil)
type SMTPMailCode struct {
Sender SMTPSender
FromAddr string
Template CodeTemplate
}
func NewSMTPMailCode(sender SMTPSender, fromAddr string, template CodeTemplate) *SMTPMailCode {
return &SMTPMailCode{
Sender: sender,
FromAddr: fromAddr,
Template: template,
}
}
func (es *SMTPMailCode) SendToEmail(ctx context.Context, toAddr string, code string) error {
var span openTracing.Span
if ctx, span = ntrace.NewMethodSpanFromContext(ctx); span != nil {
defer span.Finish()
}
var createMessage, createErr = es.Template.Format(code)
if createErr != nil {
return nerror.WrapOnly(createErr)
}
return es.Sender.Deliver(ctx, es.FromAddr, []byte(createMessage), toAddr)
}
type SMTPSender struct {
Port int
User string
Password string
Host string
Auth smtp.Auth // optional auth to be used if provided else PlainAuth is generated
}
// Deliver sends giving message to target number using target telco carrier
// email delivery mechanism.
//
// fromAddr: is your email address
// number: the sets of numbers with carrier to send desired message (e.g [email protected].
// message: the simple text message to be sent.
//
func (es *SMTPSender) Deliver(ctx context.Context, fromAddr string, message []byte, toAddrs ...string) error {
var span openTracing.Span
if ctx, span = ntrace.NewMethodSpanFromContext(ctx); span != nil {
defer span.Finish()
}
var hostAddr = fmt.Sprintf("%s:%d", es.Host, es.Port)
var smtpAuth smtp.Auth
if es.Auth == nil {
smtpAuth = smtp.PlainAuth("", es.User, es.Password, es.Host)
}
var sendErr = smtp.SendMail(hostAddr, smtpAuth, fromAddr, toAddrs, message)
if sendErr != nil {
return nerror.WrapOnly(sendErr)
}
return nil
}