package main //原始代码 https://www.jianshu.com/p/0fc63a13c82e import ( "fmt" "log" "mtool/conf" "mtool/util" "os" "strconv" "time" "gopkg.in/gomail.v2" ) // 邮件正文 // rfile 邮件附件名称 func mailbody(rfile string) string { ctime := time.Now().Format("2006-01-02 15:04:05") body := fmt.Sprintf("At %s,send to you! And the file's HASH:%s", ctime, util.CalacHash(rfile)) return body } func main() { // 从上下文中读取发送的文件 args := os.Args if args == nil || len(args) < 2 { fmt.Printf("Usage: ./mtool -f demo.tar.gz -c /www/mail.conf \n") os.Exit(1) } //操作配置文件 if args[3] == "-c" { confpath := args[4] config, err := conf.InitConfig(confpath) if err != nil { fmt.Printf("read config file faild.%s\n", err) } //邮件的附件 if args[1] == "-f" { // 待发送的文件 arfile := os.Args[2] // 发送文件 bdstr := mailbody(arfile) port, _ := strconv.Atoi(config["SMTP_port"]) subject := fmt.Sprintf("%smysql databakup(without PLANTS'COIN)", time.Now().Format("20060102150405")) m := gomail.NewMessage() m.SetHeader("From", m.FormatAddress(config["fromEmail"], config["fromName"])) // 添加别名 m.SetAddressHeader("Cc", config["fromEmail"], config["fromName"]) //抄送自己一份 m.SetHeader("To", config["toEmail"]) // 发送给用户(可以多个) m.SetHeader("Subject", subject) // 设置邮件主题 m.SetBody("text/html", bdstr) // 设置邮件正文 m.Attach(arfile) //邮件的attache // 发送邮件 d := gomail.NewDialer(config["SMTP_host"], port, config["fromEmail"], config["password"]) // 设置邮件正文 err := d.DialAndSend(m) if err != nil { log.Print(err) fmt.Printf("send mail failed! %s\n", err) return } fmt.Printf("send successfully!\n") } else { os.Exit(1) } // end } }