当前位置:主页 > 脚本语言 > Golang >

go语言发送smtp邮件的实现示例

时间:2021-05-13 08:14:55 | 栏目:Golang | 点击:

最近看了下go发送smtp邮件,于是总结一下

简单示例

先上一个最简单的代码 (网上搂的代码改了改)

package main

import (
  "fmt"
  "net/smtp"
)

const (
  // 邮件服务器地址
  SMTP_MAIL_HOST = "smtp.qq.com"
  // 端口
  SMTP_MAIL_PORT = "587"
  // 发送邮件用户账号
  SMTP_MAIL_USER = "1348581672@qq.com"
  // 授权密码
  SMTP_MAIL_PWD = "xxxx"
  // 发送邮件昵称
  SMTP_MAIL_NICKNAME = "lewis"
)

func main() {
  //声明err, subject,body类型,并为address,auth以及contentType赋值, 
  //subeject是主题,body是邮件内容, address是收件人
  
  var err error
  var subject, body string
  address := "lewissunp@outlook.com"
  auth := smtp.PlainAuth("", SMTP_MAIL_USER, SMTP_MAIL_PWD, SMTP_MAIL_HOST)
  contentType := "Content-Type: text/html; charset=UTF-8"

  //要发送的消息,可以直接写在[]bytes里,但是看着太乱,因此使用格式化
  s := fmt.Sprintf("To:%s\r\nFrom:%s<%s>\r\nSubject:%s\r\n%s\r\n\r\n%s",
    address, SMTP_MAIL_NICKNAME, SMTP_MAIL_USER, subject, contentType, body)
  msg := []byte(s)

  //邮件服务地址格式是"host:port",因此把addr格式化为这个格式,直接赋值也行。
  addr := fmt.Sprintf("%s:%s", SMTP_MAIL_HOST, SMTP_MAIL_PORT)

  //发送邮件
  err = smtp.SendMail(addr, auth, SMTP_MAIL_USER, []string{address}, msg)
  if err != nil {
    fmt.Println(err)
  } else {
    fmt.Println("send email succeed")
  }
}

收到邮件截图

简要说明

 稍加改进

我们来加点常用的功能

package main

import (
  "fmt"
  "net/smtp"
)

const (
  // 邮件服务器地址
  SMTP_MAIL_HOST = "smtp.qq.com"
  // 端口
  SMTP_MAIL_PORT = "587"
  // 发送邮件用户账号
  SMTP_MAIL_USER = "1348581672@qq.com"
  // 授权密码
  SMTP_MAIL_PWD = "jhguvicvhrnwgaeh"
  // 发送邮件昵称
  SMTP_MAIL_NICKNAME = "lewis"
)

func main() {
  address := []string{"norton_s@qq.com", "lewissunp@outlook.com"}
  subject := "test mail"
  body :=
    `<br>hello!</br>
  <br>this is a test email, pls ignore it.</br>`
  SendMail(address, subject, body)

}

func SendMail(address []string, subject, body string) (err error) {
  // 认证, content-type设置
  auth := smtp.PlainAuth("", SMTP_MAIL_USER, SMTP_MAIL_PWD, SMTP_MAIL_HOST)
  contentType := "Content-Type: text/html; charset=UTF-8"

  // 因为收件人,即address有多个,所以需要遍历,挨个发送
  for _, to := range address {
    s := fmt.Sprintf("To:%s\r\nFrom:%s<%s>\r\nSubject:%s\r\n%s\r\n\r\n%s", to, SMTP_MAIL_NICKNAME, SMTP_MAIL_USER, subject, contentType, body)
    msg := []byte(s)
    addr := fmt.Sprintf("%s:%s", SMTP_MAIL_HOST, SMTP_MAIL_PORT)
    err = smtp.SendMail(addr, auth, SMTP_MAIL_USER, []string{to}, msg)
    if err != nil {
      return err
    }
  }
  return err
}

收到邮件截图

简要说明

您可能感兴趣的文章:

相关文章