Gomail is a simple and efficient package to send emails. It is well tested and documented.
Gomail can only send emails using an SMTP server. But the API is flexible and it is easy to implement other methods for sending emails using a local Postfix, an API, etc.
It is versioned using gopkg.in so I promise there will never be backward incompatible changes within each version.
It requires Go 1.2 or newer. With Go 1.5, no external dependencies are used.
Gomail supports:
- Attachments
- Embedded images
- HTML and text templates
- Automatic encoding of special characters
- SSL and TLS
- Sending multiple emails with the same SMTP connection
https://pkg.go.dev/github.com/glpkg/gomail
go get github.com/glpkg/gomail
package main
import (
"github.com/glpkg/gomail"
)
var conf = gomail.Config{
Host: "smtp.exmail.qq.com",
Port: 465,
Username: "邮箱账号",
Password: "邮箱密码",
FromName: "发件人名称",
}
// Send 发送邮件
func Send(title, content, toMailAddr string) error {
return SendAttach(title, content, toMailAddr, "")
}
// SendAttach 发邮件带附件
func SendAttach(title, content, toMailAddr, attachURL string) error {
return SendAttachSpec(title, content, toMailAddr, attachURL, "")
}
// SendAttachSpec 发送邮件附件且可命名附件名
func SendAttachSpec(title, content, toMailAddr, attachURL, fileName string) error {
arg := gomail.MessageArg{
To: []string{toMailAddr},
Title: title,
Body: content,
}
if attachURL != "" {
arg.Attachs = append(arg.Attachs, gomail.Attach{Path: attachURL, Name: fileName})
}
return send(arg)
}
func send(arg gomail.MessageArg) error {
msg := gomail.NewMessageWithArg(arg)
dialer := gomail.NewDialer(conf)
err := dialer.DialAndSend(msg)
return err
}
func main() {
Send("邮件标题", "邮件内容", "接收者邮件地址")
}
If you get this error it means the certificate used by the SMTP server is not
considered valid by the client running Gomail. As a quick workaround you can
bypass the verification of the server's certificate chain and host name by using
SetTLSConfig
:
package main
import (
"crypto/tls"
"gopkg.in/gomail.v2"
)
func main() {
d := gomail.NewDialer("smtp.example.com", 587, "user", "123456")
d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
// Send emails using d.
}
Note, however, that this is insecure and should not be used in production.
Contributions are more than welcome! See CONTRIBUTING.md for more info.
See CHANGELOG.md.