beego发送邮件和上传文件接口

本文主要介绍采用beego框架的邮件发送和文件上传接口
发送邮件用到"gopkg.in/gomail.v2"包
在models中定义好请求参数模型和返回结果模型

type SmtpRecv struct {
   From        string   `json:"from"`
   To          []string `json:"to"`
   Cc          []string `json:"cc"`
   Pwd         string   `json:"pwd"`
   Attachments []string `json:"attachments"`
   Subject string `json:"subject"`
   Body    string `json:"body"`
}

返回结果模型如下,其中code 含义 1 成功 0 失败

type GeneralResp struct {
   Code  int         `json:"code"`
   Data  interface{} `json:"data"`
   Error string      `json:"error"`
}

beego框架API接口

type SendController struct {
   beego.Controller
}

func (this *SendController) SendMessage() {
   var smtpRecv models.SmtpRecv
   err := json.Unmarshal(this.Ctx.Input.RequestBody, &smtpRecv)
   if err != nil {
      log4go.Error(err.Error(), "smtpRecv RequestBody error")
      this.Data["json"] = models.GeneralResp{Code: 0, Error: err.Error()}
      this.ServeJSON()
      return
   }

   // send email
   err = smtpPush(smtpRecv)
   if err != nil {
      this.Data["json"] = models.GeneralResp{Code: 0, Error: err.Error()}
   } else {
      if len(smtpRecv.Attachments) != 0 {
         tools.RemoveFile(smtpRecv.Attachments)
      }
      this.Data["json"] = models.GeneralResp{Code: 1, Error: "send email success!"}
   }
   this.ServeJSON()

}

func smtpPush(smtpRecv models.SmtpRecv) error {
   m := gomail.NewMessage()
   m.SetHeaders(map[string][]string{
      "From":    {smtpRecv.From},
      "To":      smtpRecv.To,
      "Cc":      smtpRecv.Cc,
      "Subject": {smtpRecv.Subject},
   })
   //m.Attach()
   m.SetBody("text/html", smtpRecv.Body)
   if len(smtpRecv.Attachments) != 0 {
      for k, _ := range smtpRecv.Attachments {
         m.Attach(smtpRecv.Attachments[k])
      }
   }

   port, err := beego.AppConfig.Int("sendmsgport")
   if err != nil {
      log4go.Error(err.Error())
      return err
   }

   d := gomail.NewDialer(Host: "smtp.qq.com", Port: 465, Username: "[email protected]", Password: "***********",SSL:true)

   // Send the email
   if err := d.DialAndSend(m); err != nil {
      log4go.Error(err.Error())
      return err
   }
   return nil
}

type Sizer interface {
   Size() int64
}

func (this *SendController) UploadFiles() {
   f, h, err := this.GetFile("file") //获取上传的文件this.GetFile("file")
   if err != nil {
      this.Data["json"] = models.GeneralResp{Code: 0, Error: "get file fail!"}
      this.ServeJSON()
      return
   }
   defer f.Close() //关闭上传的文件,不然的话会出现临时文件不能清除的情况
   ext := path.Ext(h.Filename)
   //验证后缀名是否符合要求
   var AllowExtMap map[string]bool = map[string]bool{
      ".jpg":  true,
      ".jpeg": true,
      ".png":  true,
      ".gif":  true,
      ".csv":  true,
      ".docx": true,
      ".xlsx": true,
      ".xls":  true,
      ".doc":  true,
      ".pdf":  true,
      ".txt":  true,
      ".html": true,
      ".ppt":  true,
      ".pptx": true,
   }
   var Filebytes = 1 << 24 //文件小于16兆
   if _, ok := AllowExtMap[ext]; !ok {
      this.Data["json"] = models.GeneralResp{Code: 0, Error: "not allowed file format!"}
      this.ServeJSON()
      return
   }

   if fileSizer, ok := f.(Sizer); ok {
      fileSize := fileSizer.Size()
      if fileSize > int64(Filebytes) {
         this.Data["json"] = models.GeneralResp{Code: 0, Error: "upload file error: file size exceeds 16M!"}
         this.ServeJSON()
      } else {
         uploadDir := "./upload/" + time.Now().Format("2006/01/02/")
         err = os.MkdirAll(uploadDir, os.ModePerm)
         if err != nil {
            this.Data["json"] = models.GeneralResp{Code: 0, Error: "create upload dir fail:" + err.Error()}
            this.ServeJSON()
            return
         }
         fpath := uploadDir + h.Filename
         err = this.SaveToFile("file", fpath)
         if err != nil {
            this.Data["json"] = models.GeneralResp{Code: 0, Error: err.Error()}
            this.ServeJSON()
            //this.Ctx.WriteString(fmt.Sprintf("%v", err))
         }
         this.Data["json"] = models.GeneralResp{Code: 1, Data: fpath}
         this.ServeJSON()
      }
   } else {
      this.Data["json"] = models.GeneralResp{Code: 0, Error: "unable to read file size!"}
      this.ServeJSON()
   }

}

如有不对欢迎指正,相互学习,共同进步。

猜你喜欢

转载自blog.csdn.net/wade3015/article/details/84889982
今日推荐