Go语言发邮件

    发送邮件是实际业务中经常会用到的一个功能,而在Go语言中实现发送邮件的库也有很多,这篇文章将介绍go语言中如何发邮件。

1. 登录QQ邮箱,选择账户,开启POP3/SMTP服务和IMAP/SMTP服务,并生成授权码

 2. 使用go语言的smtp包发送邮件

  • go_email/email.go
func SendEduEmail(user, password, host, to, subject, body, mailtype string) error {
	hp := strings.Split(host, ":")
	auth := smtp.PlainAuth("", user, password, hp[0])
	var content_type string
	if mailtype == "html" {
		content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8"
	} else {
		content_type = "Content-Type: text/plain" + "; charset=UTF-8"
	}

	msg := []byte("To: " + to + "\r\nFrom: " + user + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
	send_to := strings.Split(to, ";")
	err := smtp.SendMail(host, auth, user, send_to, msg)
	return err
}
  • main.go
package main

import (
	"fmt"
)

func main() {
    send_email_test1()
}


iunc send_email_test1()  {
	var to  = []string{"15735177116@163.com", "201800910862@b.sxmu.edu.cn"}
	from := "1271570224@qq.com"
	nickname := "张亚飞"
	secret := "xxxxxxxx"
	host := "smtp.qq.com"
	port := 25
	subject := "Perfect Vue Admin 发送邮件测试"
	body := "测试内容"
	if err := go_email.SendEmail(from, to, secret, host, nickname, subject, body, port,  true); err != nil{
		fmt.Println("发送失败: ", err)
	}else {
		fmt.Println("发送成功")
	}
}

3. 使用"jordan-wright/email"发送邮件

关键参数

// Email is the type used for email messages
type Email struct {
	ReplyTo     []string
	From        string
	To          []string
	Bcc         []string
	Cc          []string
	Subject     string
	Text        []byte // Plaintext message (optional)
	HTML        []byte // Html message (optional)
	Sender      string // override From as SMTP envelope sender (optional)
	Headers     textproto.MIMEHeader
	Attachments []*Attachment
	ReadReceipt []string
}
  • From:发件人邮箱,格式为“名称+<邮箱>”,也可以直接写邮箱,默认显示的发件人为@符号前的名称
  • To:收件人邮箱地址
  • Subject:邮件标题
  • Text:邮件正文

调用Send方法发送邮件,第一个参数是你的发件人邮箱的SMTP域名+端口号,第二个参数用于身份认证

e.Send("smtp.163.com:25", smtp.PlainAuth("", "pingyeaa@163.com", "<你的密码>", "smtp.163.com"))

smtp.PlainAuth

  • 参数1:通常,identity应该是空字符串,以用作用户名。
  • 参数2:用户邮箱
  • 参数3:密码,如果拿到了授权码,则填写授权码
  • 参数4:服务器地址,163的地址是smtp.163.com,其他平台可自行查看

CC与BCC

CC全称是Carbon Copy,意为抄送,BCC全称Blind Carbon Copy,意为暗抄送,收件人看不到被暗抄送给了谁。

e := email.NewEmail()
e.Cc = []string{"xxxxxxx@qq.com"}
e.Bcc = []string{"xxxxxxx@qq.com"}

另一种初始化方式

可以实例化的时候直接赋值

e := &email.Email{
  From:    "平也 <pingyeaa@163.com>",
  To:      []string{"xxxxxxx@qq.com"},
  Subject: "发现惊天大秘密!",
  Text:    []byte("平也好帅好有智慧哦~"),
}

发送附件

发送附件非常简单,直接传入文件名即可

e.AttachFile("attachment.txt")

连接池

由于频繁发送邮件会不断的与SMTP服务器建立连接,比较影响性能,所以email提供了连接池的功能

auth := smtp.PlainAuth("", "pingyeaa@163.com", "<你的密码>", "smtp.163.com")
p, _ := email.NewPool("smtp.163.com:25", 4, auth)

创建成功后,就可以借助连接池来发送邮件

e := email.NewEmail()
e.From = "平也 <pingyeaa@163.com>"
e.To = []string{"xxxxxx@qq.com"}
e.Subject = "发现惊天大秘密!"
e.Text = []byte("平也好帅好有智慧哦~")

p.Send(e, 10*time.Second)

实例

  • go_email/email.go
package go_email

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

var (
	pool *email.Pool
	maxClient int = 10
)


func SendEmail(from string, to []string, secret string, host string, nickname string, subject string, body string, port int, ssl bool) error {
	auth := smtp.PlainAuth("", from, secret, host)
	e := email.NewEmail()
	e.From = fmt.Sprintf("%s<%s>", nickname, from)
	e.To = to
	e.Subject = subject
	e.HTML = []byte(body)
	hostAddr := fmt.Sprintf("%s:%d", host, port)
	if ssl {
		return e.SendWithTLS(hostAddr, auth,&tls.Config{ServerName: host})
	}
	return e.Send(hostAddr, auth)
}

func SendEmailWithFile(from string, to []string, secret string, host string, nickname string, subject string, body string, port int, ssl bool,attach string) error {
	auth := smtp.PlainAuth("", from, secret, host)
	e := email.NewEmail()
	e.From = fmt.Sprintf("%s<%s>", nickname, from)
	e.To = to
	e.Subject = subject
	e.HTML = []byte(body)
	if attach != ""{
		_,_ = e.AttachFile(attach)
	}
	hostAddr := fmt.Sprintf("%s:%d", host, port)
	if ssl {
		return e.SendWithTLS(hostAddr, auth,&tls.Config{ServerName: host})
	}
	return e.Send(hostAddr, auth)
}

func SendEmailWithPool(to []string, from, secret, host, subject, body, nickname string, port int) (err error) {
	hostAddr := fmt.Sprintf("%s:%d", host, port)
	auth := smtp.PlainAuth("", from, secret, host)
	if pool == nil {
		pool, err = email.NewPool(hostAddr, maxClient, auth)
		if err != nil {
			log.Fatal(err)
		}
	}
	e := &email.Email{
		From: fmt.Sprintf("%s<%s>", nickname, from),
		To:      to,
		Subject: subject,
		Text:    []byte(body),
	}
	return pool.Send(e, 5 * time.Second)
}

func SendEmailWithPoolAndFile(to []string, from, secret, host, subject, body, nickname string, port int, attach string) (err error) {
	hostAddr := fmt.Sprintf("%s:%d", host, port)
	auth := smtp.PlainAuth("", from, secret, host)
	if pool == nil {
		pool, err = email.NewPool(hostAddr, maxClient, auth)
		if err != nil {
			log.Fatal(err)
		}
	}
	e := &email.Email{
		From: fmt.Sprintf("%s<%s>", nickname, from),
		To:      to,
		Subject: subject,
		Text:    []byte(body),
	}
	if attach != "" {
		_, _ = e.AttachFile(attach)
	}
	return pool.Send(e, 5 * time.Second)
}
  • main.go
package main

import (
	"fmt"
	go_email "go_dev/go_email/email"
)

func main() {
	//send_email_test1()
	//send_email_test2()
	//send_email_test3()
	send_email_test4()
}

func send_email_test4()  {
	var to  = []string{"15735177116@163.com", "1271570224@qq.com"}
	from := "201800910862@b.sxmu.edu.cn"
	nickname := "张亚飞"
	secret := "xxxxxxxx"
	host := "smtp.exmail.qq.com"
	port := 25
	subject := "Perfect Vue Admin 发送邮件测试"
	body := "测试内容"
	if err := go_email.SendEmailWithPoolAndFile(to, from, secret, host, subject, body, nickname, port, "简称.txt"); err != nil{
		fmt.Println("发送失败: ", err)
	}else {
		fmt.Println("发送成功")
	}
}

func send_email_test3()  {
	var to  = []string{"15735177116@163.com", "201800910862@b.sxmu.edu.cn"}
	from := "1271570224@qq.com"
	nickname := "张亚飞"
	secret := "vsloiltxbxyzgeii"
	host := "smtp.qq.com"
	port := 25
	subject := "Perfect Vue Admin 发送邮件测试"
	body := "测试内容"
	if err := go_email.SendEmailWithPoolAndFile(to, from, secret, host, subject, body, nickname, port, "简称.txt"); err != nil{
		fmt.Println("发送失败: ", err)
	}else {
		fmt.Println("发送成功")
	}
}

func send_email_test2()  {
	to  := "1271570224@qq.com;15735177116@163.com"
	user := "201800910862@b.sxmu.edu.cn"
	password := "xxxxxx3"
	host := "smtp.exmail.qq.com:25"
	//host := "smtp.exmail.qq.com"
	subject := "Perfect Vue Admin 发送邮件测试"
	body := "测试内容"
	if err := go_email.SendEduEmail(user, password, host, to, subject, body, "html"); err != nil{
		fmt.Println("发送失败: ", err)
	}else {
		fmt.Println("发送成功")
	}
}

func send_email_test1()  {
	var to  = []string{"15735177116@163.com", "201800910862@b.sxmu.edu.cn"}
	from := "1271570224@qq.com"
	nickname := "张亚飞"
	secret := "xxxxxx"
	host := "smtp.qq.com"
	port := 25
	subject := "Perfect Vue Admin 发送邮件测试"
	body := "测试内容"
	if err := go_email.SendEmail(from, to, secret, host, nickname, subject, body, port,  true); err != nil{
		fmt.Println("发送失败: ", err)
	}else {
		fmt.Println("发送成功")
	}

四、常用邮箱服务器地址与端口

163.com: 

POP3服务器地址:pop.163.com(端口:110) 

SMTP服务器地址:smtp.163.com(端口:25)  

 

126邮箱:

POP3服务器地址:pop.126.com(端口:110) 

SMTP服务器地址:smtp.126.com(端口:25)

 

139邮箱: 

POP3服务器地址:POP.139.com(端口:110) 

SMTP服务器地址:SMTP.139.com(端口:25) 

 

QQ邮箱: 

POP3服务器地址:pop.qq.com(端口:110) 

SMTP服务器地址:smtp.qq.com (端口:25)  

 

QQ企业邮箱 :

POP3服务器地址:pop.exmail.qq.com (SSL启用 端口:995) 

SMTP服务器地址:smtp.exmail.qq.com(SSL启用 端口:587/465)  

 

gmail(google.com) :

POP3服务器地址:pop.gmail.com(SSL启用 端口:995) 

SMTP服务器地址:smtp.gmail.com(SSL启用 端口:587) 

 

Foxmail: 

POP3服务器地址:POP.foxmail.com(端口:110) 

SMTP服务器地址:SMTP.foxmail.com(端口:25) 

 

sina.com: 

POP3服务器地址:pop3.sina.com.cn(端口:110) 

SMTP服务器地址:smtp.sina.com.cn(端口:25)

 

sinaVIP: 

POP3服务器:pop3.vip.sina.com (端口:110) 

SMTP服务器:smtp.vip.sina.com (端口:25)  

 

sohu.com: 

POP3服务器地址:pop3.sohu.com(端口:110) 

SMTP服务器地址:smtp.sohu.com(端口:25)  

 

yahoo.com: 

POP3服务器地址:pop.mail.yahoo.com 

SMTP服务器地址:smtp.mail.yahoo.com  

 

yahoo.com.cn: 

POP3服务器地址:pop.mail.yahoo.com.cn(端口:995) 

SMTP服务器地址:smtp.mail.yahoo.com.cn(端口:587  )

 

HotMail :

POP3服务器地址:pop3.live.com (端口:995) 

SMTP服务器地址:smtp.live.com (端口:587263.net: 

POP3服务器地址:pop3.263.net(端口:110) 

SMTP服务器地址:smtp.263.net(端口:25263.net.cn: 

POP3服务器地址:pop.263.net.cn(端口:110) 

SMTP服务器地址:smtp.263.net.cn(端口:25)  

 

x263.net: 

POP3服务器地址:pop.x263.net(端口:110) 

SMTP服务器地址:smtp.x263.net(端口:25) 

 

21cn.com: 

POP3服务器地址:pop.21cn.com(端口:110) 

SMTP服务器地址:smtp.21cn.com(端口:25)   


china.com: 

POP3服务器地址:pop.china.com(端口:110) 

SMTP服务器地址:smtp.china.com(端口:25)

  
tom.com: 

POP3服务器地址:pop.tom.com(端口:110) 

SMTP服务器地址:smtp.tom.com(端口:25)

  
etang.com: 

POP3服务器地址:pop.etang.com 

SMTP服务器地址:smtp.etang.com
常用邮箱的服务器地址与端口

  

posted @ 2020-11-03 10:29  DreamBoy_张亚飞  阅读(2235)  评论(0编辑  收藏  举报