| 1 | package mailyak |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "net" |
| 6 | ) |
| 7 | |
| 8 | // senderWithStartTLS connects to the remote SMTP server, upgrades the |
| 9 | // connection using STARTTLS if available, and sends the email. |
| 10 | type senderWithStartTLS struct { |
| 11 | hostAndPort string |
| 12 | hostname string |
| 13 | buf *bytes.Buffer |
| 14 | } |
| 15 | |
| 16 | func (s *senderWithStartTLS) Send(m sendableMail) error { |
| 17 | conn, err := net.Dial("tcp", s.hostAndPort) |
| 18 | if err != nil { |
| 19 | return err |
| 20 | } |
| 21 | defer func() { _ = conn.Close() }() |
| 22 | |
| 23 | return smtpExchange(m, conn, s.hostname, true) |
| 24 | } |
| 25 | |
| 26 | func newSenderWithStartTLS(hostAndPort string) *senderWithStartTLS { |
| 27 | hostName, _, err := net.SplitHostPort(hostAndPort) |
| 28 | if err != nil { |
| 29 | // Really this should be an error, but we can't return it from the New() |
| 30 | // constructor without breaking compatability. Fortunately by the time |
| 31 | // it gets to the dial() the user will get a pretty clear error as this |
| 32 | // hostAndPort value is almost certainly invalid. |
| 33 | // |
| 34 | // This hostname must be split from the port so the correct value is |
| 35 | // used when performing the SMTP AUTH as the Go SMTP implementation |
| 36 | // refuses to send credentials over non-localhost plaintext connections, |
| 37 | // and including the port messes this check up (and is probably the |
| 38 | // wrong thing to be sending anyway). |
| 39 | hostName = hostAndPort |
| 40 | } |
| 41 | |
| 42 | return &senderWithStartTLS{ |
| 43 | hostAndPort: hostAndPort, |
| 44 | hostname: hostName, |
| 45 | buf: &bytes.Buffer{}, |
| 46 | } |
| 47 | } |