邮件推送在任何一个软件项目中都是必须实现的模块。比如登录注册,广告推送,消息提醒等等。
这里小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")
需要的话,可以在这里下载:地址
|
请发表评论