These code works normally when using gmail (with AllowLessSecureApp turned on), but doesn't work with mailhog (unencrypted connection
error), these the minimal code to reproduce:
package main
import (
"crypto/tls"
"fmt"
"net/smtp"
"github.com/jordan-wright/email"
"github.com/stretchr/testify/assert"
)
func TestSendMail(t *testing.T) {
m := struct{
Host string
Port int
User string
Pass string
}{
Host: `local.test`, // resolved to 127.0.0.1 in /etc/hosts
Port: 1025,
User: `[email protected]`,
Pass: `test`,
}
e := email.NewEmail()
e.From = `[email protected]`
e.To = []string{`[email protected]`}
e.Subject = `test mail`
host, _ := os.Hostname()
e.Text = []byte(`testing email from ` + host)
err := e.SendWithStartTLS(fmt.Sprintf("%s:%d", m.Host, m.Port), smtp.PlainAuth("", m.User, m.Pass, m.Host), &tls.Config{InsecureSkipVerify: true})
assert.NoError(t, err)
}
The docker-compose.yml
:
version: "3.9"
services:
mailhog:
image: mailhog/mailhog
container_name: test_mailhog
env_file:
- backend/.env # not used
ports:
- 1025:1025 # smtp server
- 8025:8025 # web ui
restart: unless-stopped
Or any workaround for this? eg. some TLS proxy on docker-compose?
it is possible that mailhog does not have proper TLS certs, and it listens without TLS on localhost, try using function https://pkg.go.dev/github.com/jordan-wright/email#Email.Send to send email
err := e.Send(fmt.Sprintf("%s:%d", m.Host, m.Port),smtp.CRAMMD5Auth(m.User,m.Pass))