golang发送邮件

本文介绍如何利用Golang的内置库net/smtp来创建和发送电子邮件,包括设置SMTP服务器、验证凭据、构建邮件消息及附件的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/smtp"
	"strconv"
	"strings"
)

func main() {
	//TimeSettle()
	Message()

}
func getPm25() int{

	client := &http.Client{}
	resp, err := client.Get("https://api.waqi.info/feed/shanghai/?token=demo")
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
	if err != nil {
		fmt.Println(err)
	}

	m := make(map[string]interface{})
	json.Unmarshal([]byte(body), &m)
	a :=m["data"].(map[string]interface{})["iaqi"].(map[string]interface{})["pm25"].(map[string]interface{})["v"]
	//fmt.Println(m["data"].(map[string]interface{})["iaqi"].(map[string]interface{})["pm25"].(map[string]interface{})["v"])
	//fmt.Println(reflect.TypeOf(m))
	b :=int(a.(float64))
	return b
}

//发送邮件
func sendToMail(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 + "<"+
		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
}

func sendEmail(subject,body string)  {
	user := "xxxxxx@163.com" //发送邮件的邮箱
	pwd := "OIASLHSAUYQHEQSAxxxxxx" //授权码
	host := "smtp.163.com:25"
	to := "xxxxxxx@qq.com;xxxxx@163.com"//接收邮件的邮箱,可以用;隔开发送多个
	fmt.Println("send email")
	err := sendToMail(user,pwd,host,to,subject,body,"html")
	if err != nil {
		fmt.Println("Send mail error!")
		fmt.Println(err)
	} else {
		fmt.Println("Send mail success!")
	}
}
// 定时结算(一天发一次)
//func TimeSettle() {
//	d := time.Duration(time.Minute)
//	t := time.NewTicker(d)
//	defer t.Stop()
//	for {
//		//currentTime := time.Now()
//		pm25 :=getPm25()
//		if pm25>50 {
//			//	if currentTime.Hour() == 8 { // 8点发送
//			Sendinfo(pm25)
//			time.Sleep(time.Hour)
//			//}
//		}
//		<-t.C
//	}
//}

func Message(){
	pm25 :=getPm25()
	Templete(pm25)

}

func Templete(pm25 int){
	subject, body := "空气质量预警","今日pm25高达"+  strconv.Itoa(pm25) +",请尽量减少户外活动"
	sendEmail(subject, body)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值