- Func
- Dialer">type Dialer
- FileSetting">type FileSetting
- Message">type Message
- Demo
文档:https://pkg.go.dev/gopkg.in/gomail.v2
Func
func Send(s Sender, msg ...*Message) error
type Dialer
type Dialer struct {
// Host represents the host of the SMTP server.
Host string
// Port represents the port of the SMTP server.
Port int
// Username is the username to use to authenticate to the SMTP server.
Username string
// Password is the password to use to authenticate to the SMTP server.
Password string
// Auth represents the authentication mechanism used to authenticate to the
// SMTP server.
Auth smtp.Auth
// SSL defines whether an SSL connection is used. It should be false in
// most cases since the authentication mechanism should use the STARTTLS
// extension instead.
SSL bool
// TSLConfig represents the TLS configuration used for the TLS (when the
// STARTTLS extension is used) or SSL connection.
TLSConfig *tls.Config
// LocalName is the hostname sent to the SMTP server with the HELO command.
// By default, "localhost" is sent.
LocalName string
}
func NewDialer(host string, port int, username, password string) *Dialer
func (d *Dialer) Dial() (SendCloser, error)
type FileSetting
// 设置附件名称
func Rename(name string) FileSetting
// 设置附件内容
func SetCopyFunc(f func(io.Writer) error) FileSetting
// 设置包含文件内容的消息部分的MIME头
func SetHeader(h map[string][]string) FileSetting
type Message
func NewMessage(settings ...MessageSetting) *Message
// 增加附件
func (m *Message) Attach(filename string, settings ...FileSetting)
// 将图像嵌入到电子邮件中
func (m *Message) Embed(filename string, settings ...FileSetting)
m.Embed("/tmp/image.jpg")
m.SetBody("text/html", `<img src="cid:image.jpg" alt="My image" />`)
// 将地址和名称格式化为有效的RFC 5322地址
func (m *Message) FormatAddress(address, name string) string
func (m *Message) SetHeader(field string, value ...string)
func (m *Message) SetHeaders(h map[string][]string)
m.SetHeaders(map[string][]string{
"From": {m.FormatAddress("alex@example.com", "Alex")},
"To": {"bob@example.com", "cora@example.com"},
"Subject": {"Hello"},
})
// 设置消息的主体。
// 它替换任何先前设置的SetBody, AddAlternative或AddAlternativeWriter的内容
func (m *Message) SetBody(contentType, body string, settings ...PartSetting)
func (m *Message) Reset() // 情况设置,保持与NewMessage一样的状态
Demo
package main
import (
"gopkg.in/gomail.v2"
"log"
)
func main() {
d := gomail.NewDialer("smtp.qq.com", 587, "xxx@qq.com", "xxx")
s, err := d.Dial()
if err != nil {
panic(err)
}
m := gomail.NewMessage()
m.SetHeader("From", "xxx@qq.com")
m.SetHeader("To", "yyy@qq.com", "macho")
m.SetHeader("Subject", "Newsletter #1")
m.SetBody("text/html", "happy every day!")
m.Attach("./upaiyun.gif")
if err := gomail.Send(s, m); err != nil {
log.Printf("Could not send email: %v", err)
}
}