Add TLS to SMTP config

This commit is contained in:
Kailash Nadh 2020-05-17 21:07:48 +05:30
parent cb331b9341
commit 18329ff052
3 changed files with 31 additions and 12 deletions

View File

@ -84,7 +84,7 @@ max_idle = 10
[smtp.my0]
enabled = true
host = "my.smtp.server"
port = "25"
port = 25
# "cram", "plain", or "login". Empty string for no auth.
auth_protocol = "cram"
@ -112,10 +112,14 @@ max_idle = 10
# The number of times a message should be retried if sending fails.
max_msg_retries = 2
# Enable STARTTLS.
tls_enabled = true
tls_skip_verify = false
[smtp.postal]
enabled = false
host = "my.smtp.server2"
port = "25"
port = 25
# cram or plain.
auth_protocol = "plain"
@ -143,6 +147,9 @@ max_idle = 10
# The number of times a message should be retried if sending fails.
max_msg_retries = 2
# Enable STARTTLS.
tls_enabled = true
tls_skip_verify = false
[upload]
# File storage backend. "filesystem" or "s3".

3
go.mod
View File

@ -21,5 +21,4 @@ require (
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
gopkg.in/volatiletech/null.v6 v6.0.0-20170828023728-0bef4e07ae1b
jaytaylor.com/html2text v0.0.0-20200220170450-61d9dc4d7195
)
)

View File

@ -1,6 +1,7 @@
package messenger
import (
"crypto/tls"
"fmt"
"math/rand"
"net/smtp"
@ -13,11 +14,13 @@ const emName = "email"
// Server represents an SMTP server's credentials.
type Server struct {
Name string
Username string `json:"username"`
Password string `json:"password"`
AuthProtocol string `json:"auth_protocol"`
EmailFormat string `json:"email_format"`
Name string
Username string `json:"username"`
Password string `json:"password"`
AuthProtocol string `json:"auth_protocol"`
EmailFormat string `json:"email_format"`
TLSEnabled bool `json:"tls_enabled"`
TLSSkipVerify bool `json:"tls_skip_verify"`
// Rest of the options are embedded directly from the smtppool lib.
// The JSON tag is for config unmarshal to work.
@ -35,13 +38,13 @@ type Emailer struct {
// NewEmailer creates and returns an e-mail Messenger backend.
// It takes multiple SMTP configurations.
func NewEmailer(srv ...Server) (*Emailer, error) {
func NewEmailer(servers ...Server) (*Emailer, error) {
e := &Emailer{
servers: make(map[string]*Server),
}
for _, server := range srv {
s := server
for _, srv := range servers {
s := srv
var auth smtp.Auth
switch s.AuthProtocol {
case "cram":
@ -56,6 +59,16 @@ func NewEmailer(srv ...Server) (*Emailer, error) {
}
s.Opt.Auth = auth
// TLS config.
if s.TLSEnabled {
s.TLSConfig = &tls.Config{}
if s.TLSSkipVerify {
s.TLSConfig.InsecureSkipVerify = s.TLSSkipVerify
} else {
s.TLSConfig.ServerName = s.Host
}
}
pool, err := smtppool.New(s.Opt)
if err != nil {
return nil, err