当前位置:网站首页>Go之发送钉钉和邮箱

Go之发送钉钉和邮箱

2020-11-07 21:19:24 you-men

smtp发送邮件

群发两个邮箱,一个163,一个QQ
package main

import (
	"fmt"
	"net/smtp"
	"strings"
)

const (
	HOST        = "smtp.163.com"
	SERVER_ADDR = "smtp.163.com:25"
	USER        = "xxx@163.com"   //发送邮件的邮箱
	PASSWORD    = "xxxxx"         //发送邮件邮箱的密码
)

type Email struct {
	to      string "to"
	subject string "subject"
	msg     string "msg"
}

func NewEmail(to, subject, msg string) *Email {
	return &Email{to: to, subject: subject, msg: msg}
}

func SendEmail(email *Email) error {
	auth := smtp.PlainAuth("", USER, PASSWORD, HOST)
	sendTo := strings.Split(email.to, ";")
	done := make(chan error, 1024)

	go func() {
		defer close(done)
		for _, v := range sendTo {

			str := strings.Replace("From: "+USER+"~To: "+v+"~Subject: "+email.subject+"~~", "~", "\r\n", -1) + email.msg

			err := smtp.SendMail(
				SERVER_ADDR,
				auth,
				USER,
				[]string{v},
				[]byte(str),
			)
			done <- err
		}
	}()
	for i := 0; i < len(sendTo); i++ {
		<-done
	}
	return nil
}

func main() {
	mycontent := "this is go test email"
	email := NewEmail("xxx@163.com;xxx@qq.com;",
		"test golang email", mycontent)
	err := SendEmail(email)
	fmt.Println(err)
}
验证邮箱

发送钉钉简介

钉钉报警设置

创建群机器人

接口地址

发送短消息

发送普通消息
package main

import (
	"fmt"
	"net/http"
	"strings"
)

func main() {
	SendDingMsg("zhou","1234")
}

func SendDingMsg(name ,msg string) {
	//请求地址模板
	webHook := `https://xxxx`
	content := `{"msgtype": "text",
		"text": {"content": "` + name+ ":" + msg + `"}
	}`
	//创建一个请求
	req, err := http.NewRequest("POST", webHook, strings.NewReader(content))
	if err != nil {
		// handle error
	}

	client := &http.Client{}
	//设置请求头
	req.Header.Set("Content-Type", "application/json; charset=utf-8")
	//发送请求
	resp, err := client.Do(req)
	//关闭请求
	defer resp.Body.Close()

	if err != nil {
		// handle error
		fmt.Println(err)
	}
}

版权声明
本文为[you-men]所创,转载请带上原文链接,感谢
https://www.cnblogs.com/you-men/p/13942340.html