| 1 | package mailyak |
| 2 | |
| 3 | import ( |
| 4 | "crypto/tls" |
| 5 | "net" |
| 6 | ) |
| 7 | |
| 8 | // senderExplicitTLS connects to a SMTP server over a TLS connection, performs a |
| 9 | // handshake and validation according to the provided tls.Config before sending |
| 10 | // the email. |
| 11 | type senderExplicitTLS struct { |
| 12 | hostAndPort string |
| 13 | hostname string |
| 14 | |
| 15 | // tlsConfig is always non-nil |
| 16 | tlsConfig *tls.Config |
| 17 | } |
| 18 | |
| 19 | // Connect to the SMTP host configured in m, and send the email. |
| 20 | func (s *senderExplicitTLS) Send(m sendableMail) error { |
| 21 | conn, err := tls.Dial("tcp", s.hostAndPort, s.tlsConfig) |
| 22 | if err != nil { |
| 23 | return err |
| 24 | } |
| 25 | defer func() { _ = conn.Close() }() |
| 26 | |
| 27 | // Perform the SMTP protocol conversation, using the provided TLS ServerName |
| 28 | // as the SMTP server name. |
| 29 | return smtpExchange(m, conn, s.hostname, false) |
| 30 | } |
| 31 | |
| 32 | // newSenderWithExplicitTLS constructs a new senderExplicitTLS. |
| 33 | // |
| 34 | // If tlsConfig is nil, a sensible default with maximum compatability is |
| 35 | // generated. |
| 36 | func newSenderWithExplicitTLS(hostAndPort string, tlsConfig *tls.Config) (*senderExplicitTLS, error) { |
| 37 | // Split the hostname from the addr. |
| 38 | // |
| 39 | // This hostname is used during TLS negotiation and during SMTP |
| 40 | // authentication. |
| 41 | hostName, _, err := net.SplitHostPort(hostAndPort) |
| 42 | if err != nil { |
| 43 | return nil, err |
| 44 | } |
| 45 | |
| 46 | if tlsConfig != nil { |
| 47 | // Clone the user-provided TLS config to prevent it being |
| 48 | // mutated by the caller. |
| 49 | tlsConfig = tlsConfig.Clone() |
| 50 | } else { |
| 51 | // If there is no TLS config provided, initialise a default. |
| 52 | //nolint:gosec // Maximum compatability but please use TLS >= 1.2 |
| 53 | tlsConfig = &tls.Config{ |
| 54 | ServerName: hostName, |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | return &senderExplicitTLS{ |
| 59 | hostAndPort: hostAndPort, |
| 60 | hostname: hostName, |
| 61 | |
| 62 | tlsConfig: tlsConfig, |
| 63 | }, nil |
| 64 | } |