• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

go语言实现邮件推送模块,已编译成exe可执行程序,开箱即用

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

邮件推送在任何一个软件项目中都是必须实现的模块。比如登录注册,广告推送,消息提醒等等。

这里小coder分享一下go语言实现qq邮箱发送邮件功能。

代码结构:

main.go 

//author:一只小coder
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/smtp"
	"os"
	"strings"
)

type Config struct {
	Email    string `json:"email"`
	NickName string `json:"nick_name"`
	Password string `json:"password"`
}

func LoadConfig(configPath string) (config *Config) {
	data, err := ioutil.ReadFile(configPath)
	if err != nil {
		log.Fatal(err)
	}
	config = &Config{}
	err = json.Unmarshal(data, &config)
	if err != nil {
		log.Fatal(err)
	}
	return config
}

func SendEmail(config *Config, email, title, content string) {
	auth := smtp.PlainAuth("", config.Email, config.Password, "smtp.qq.com")
	to := []string{email}
	user := config.Email
	nickname := config.NickName
	subject := title
	content_type := "Content-Type: text/plain; charset=UTF-8"
	body := content
	msg := "To: " + strings.Join(to, ",") + "\r\nFrom: "
	msg += nickname + "<" + user + ">\r\nSubject: " + subject
	msg += "\r\n" + content_type + "\r\n\r\n" + body
	err := smtp.SendMail("smtp.qq.com:587", auth, user, to, []byte(msg))
	if err != nil {
		fmt.Printf("send mail error: %v", err)
	}
}

func main() {
	config := LoadConfig("./config.json")
	to := os.Args[1]
	title := os.Args[2]
	content := os.Args[3]
	if to != "" && title != "" && content != "" {
		SendEmail(config, to, title, content)
	} else {
		panic("to,title,content can't be null")
	}
}

config.json配置:

{
  "email":"[email protected]",
  "password":"xxx",
  "nick_name":"admin"
}

准备QQ账号和密码:

需要配置下发送邮件的账号和密码,这里的密码是在qq邮箱配置中:

 

 

 

编译生成了可执行的exe程序,放到目录email下:

 在config.json中填入账号密码,就能调用了:

 想要在python中使用的话,我再封装了下:

send_email.py文件:

# /usr/bin/python
# encoding: utf-8
from subprocess import call
import os
class SendMail:
    def __init__(self,to, title,content):
        ENV_HOME = os.environ.get("HOME", "")
        if ENV_HOME == "/root":
            cmd = '''email -to "{}" -title "{}" -content "{}"'''.format(to,title,content)
        else:
            cmd = '''email.exe -to "{}" -title "{}" -content "{}"'''.format(to, title, content)
        call(cmd, shell=True)

if __name__ == '__main__':
    SendMail("[email protected]","test","content")

需要的话,可以在这里下载:地址


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
[日常]Go语言圣经-Slice切片习题发布时间:2022-07-10
下一篇:
GoModules详解发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap