Golang 邮件发送stmp

985 阅读1分钟

一、邮件发送准备

获取相应邮箱的授权码,用QQ邮箱为例:

邮箱 -> 设置 -> 账户 -> SMTP服务 -> 生成授权码

邮箱授权码获取1.png

邮箱授权码获取2.png

二、Golang 操作发送邮箱

1. 第三方库

go get github.com/jordan-wright/email

2. 示例:

package main

import (
   "github.com/jordan-wright/email"
   "log"
   "net/smtp"
   "time"
)

const (
   SMTPHost     = "smtp.263.net"  //这个部分根据自己的需求去填写,QQ邮箱应该是`smtp.qq.com`
   SMTPPort     = ":465" // 端口号也是找到自己对应的,我这里用的是公司内部的
   SMTPUsername = "xxxx.xxxx@superxon.com" // 自己的账号
   SMTPPassword = "xxxxxxxxxxxxx" // 授权码
   MaxClient    = 5 
)

var pool *email.Pool

func SendEmail(receiver []string, Subject string, Html []byte, attachment []string) error {
   var err error
   if pool == nil {
      pool, err = email.NewPool(SMTPHost+SMTPPort, MaxClient, smtp.PlainAuth("", SMTPUsername, SMTPPassword, SMTPHost))
      if err != nil {
         log.Fatal(err)
         return err
      }
   }
   e := &email.Email{
      From:    SMTPUsername,
      To:      receiver,
      Subject: Subject,
      HTML:    Html,
   }
   if len(attachment) > 0 {
      for i := 0; i < len(attachment); i++ {
         if len(attachment[i]) > 0 {
            _, err = e.AttachFile(attachment[i])
            if err != nil {
               return err
            }
            time.Sleep(time.Second * 10)
         }
      }
   }

   err = pool.Send(e, 20*time.Second)
   if err != nil {
      log.Fatal(err)
      return err
   }
   return nil
}

func main() {
   _ = SendEmail([]string{"xxx.xxx@xxxxx.com"}, "HelloWorld", []byte("<html>HelloWorld</html>"), []string{"123.txt"})
}
参数解析
func SendEmail(receiver []string, Subject string, Html []byte, attachment []string) error
  • receiver

收件人(可以多个收件人)

  • Subject

邮件主题

  • Html

邮件正文

  • attachment

附件内容(可以多个附件)

示例结果->

邮件结果.png