简介
在通知中,邮件算是最常见的通知方式了,在Go语言中,提供了net/smtp包可以直接发送邮件。
代码
默认是纯文本类型的,我们可以通过传contentTyoe这个头信息来告诉收件者,内容是什么格式的。
package emailimport ( "net/smtp" "strings")// SendMail 发送邮件func SendMail(name, user, password, host, port, toEmails, subject, body, mailtype string) error { auth := smtp.PlainAuth("", user, password, host) var contentType string if mailtype == "html" { contentType = "Content-Type: text/" + mailtype + "; charset=UTF-8" } else { contentType = "Content-Type: text/plain" + "; charset=UTF-8" } msg := []byte("to: " + toEmails + "from: " + name + " subject: " + subject + "" + contentType + "" + body) sendTo := strings.Split(toEmails, ";") err := smtp.SendMail(host+":"+port, auth, user, sendTo, msg) return err}
测试
package mainimport ( "fmt" "email")func main() { content := `
linux OPcai
` err := email.SendMail("linux运维菜", "opcai@linux.com", "opcai@2020", "smtp.linux.com", "25", "caicai@linux.com", "这个一个测试邮件", content, "html") if err != nil { fmt.Println("发送失败") panic(err) } fmt.Println("发送成功")}
总结
如果需要更丰富的内容,可以找第三方开源的包,自带的包都是要自己处理的。