Go之傳送釘釘和郵箱

men發表於2020-11-07

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)
	}
}

相關文章