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

本文介绍了一种使用Go语言实现QQ邮箱邮件推送的方法,包括代码结构、配置读取及邮件发送过程,适用于登录注册、广告推送等场景。

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

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

这里小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":"xxx@qq.com",
  "password":"xxx",
  "nick_name":"admin"
}

准备QQ账号和密码:

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

 

 

 

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

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

go语è¨å®ç°é®ä»¶æ¨é模åï¼å·²ç¼è¯æexe坿§è¡ç¨åºï¼å¼ç®±å³ç¨

 想要在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("xxx@qq.com","test","content")

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

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值