Golang如何实现smtp邮件发送

其他教程   发布日期:2024年05月15日   浏览次数:236

本文小编为大家详细介绍“Golang如何实现smtp邮件发送”,内容详细,步骤清晰,细节处理妥当,希望这篇“Golang如何实现smtp邮件发送”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

使用函数

SendMail

连接到addr指定的服务器;如果支持会开启TLS;如果支持会使用a认证身份;然后以from为邮件源地址发送邮件msg到目标地址to。(可以是多个目标地址:群发)

邮件的msg参数应按照RFC 822协议的格式,其中首先是标头,然后是空行,接着是邮件正文,消息的行应以CRLF结束。1

SendMail 函数和 net/smtp 包是低级机制,不支持 DKIM 签名、MIME 附件(请参阅 mime/多部分包)或其他邮件功能。更高级别的包存在于标准库之外。

  1. func SendMail(addr string, a Auth, from string, to []string, msg []byte) error

PlainAuth

返回一个实现了PLAIN身份认证机制(参见RFC 4616)的Auth接口。返回的接口使用给出的用户名和密码,通过TLS连接到主机认证,采用identity为身份管理和行动(通常应设identity为"",以便使用username为身份)。

  1. func PlainAuth(identity, username, password, host string) Auth

功能实现

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/smtp"
  6. )
  7. // 邮箱服务器配置信息
  8. type configInof struct {
  9. smtpAddr string
  10. smtpPort string
  11. secret string
  12. }
  13. // 邮件内容信息
  14. type emailContent struct {
  15. fromAddr string
  16. contentType string
  17. theme string
  18. message string
  19. toAddr []string
  20. }
  21. func sendEmail(c *configInof, e *emailContent) error {
  22. // 拼接smtp服务器地址
  23. smtpAddr := c.smtpAddr + ":" + c.smtpPort
  24. // 认证信息
  25. auth := smtp.PlainAuth("", e.fromAddr, c.secret, c.smtpAddr)
  26. // 配置邮件内容类型
  27. if e.contentType == "html" {
  28. e.contentType = "Content-Type: text/html; charset=UTF-8"
  29. } else {
  30. e.contentType = "Content-Type: text/plain; charset=UTF-8"
  31. }
  32. // 当有多个收件人
  33. for _, to := range e.toAddr {
  34. msg := []byte("To: " + to + "
  35. " +
  36. "From: " + e.fromAddr + "
  37. " +
  38. "Subject: " + e.theme + "
  39. " +
  40. e.contentType + "
  41. " +
  42. "<html><h2>" + e.message + "</h2></html>")
  43. err := smtp.SendMail(smtpAddr, auth, e.fromAddr, []string{to}, msg)
  44. if err != nil {
  45. return err
  46. }
  47. }
  48. return nil
  49. }
  50. func main() {
  51. // 收集配置信息
  52. config := configInof{
  53. // smtp服务器地址
  54. smtpAddr: "smtp.yeah.net",
  55. // smtp服务器密钥
  56. secret: "xxxxxxxxxxxxxx",
  57. // smtp服务器端口
  58. smtpPort: "25",
  59. }
  60. // 收集邮件内容
  61. content := emailContent{
  62. // 发件人
  63. fromAddr: "youremail@yeah.net",
  64. // 收件人(可有多个)
  65. toAddr: []string{"xxxxxx@qq.com", "xxxxxxx@126.com"},
  66. // 邮件格式
  67. contentType: "html",
  68. // 邮件主题
  69. theme: "我是一个正经邮件",
  70. // 邮件内容
  71. message: "我有高压锅你要吗",
  72. }
  73. // 发送邮件
  74. err := sendEmail(&config, &content)
  75. if err != nil {
  76. log.Fatal(err)
  77. } else {
  78. fmt.Println("发送成功")
  79. }
  80. }

小提示

在使用网易系邮箱时,有的小伙伴会遇到这样的报错,那就是可能因为你的邮件内容没有按照RFC 822标准,可以按照我这种尝试下

2022/01/20 15:01:56 554 DT:SPM 126 smtp9,NeRpCgCnvxfkCOlh2HXIAg--.32178S3 1642662117,please see http://mail.163.com/help/help_spam_16.htm

消息标头通常应包含"发件人"、“收件人”、"主题"和"抄送"等字段。密教抄送功能是通过在 to 参数中包含多个电子邮件地址实现,而不是将其包含在消息标头中来完成的。

以上就是Golang如何实现smtp邮件发送的详细内容,更多关于Golang如何实现smtp邮件发送的资料请关注九品源码其它相关文章!