另客网go项目公用的代码库

email.go 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package notice
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io/ioutil"
  7. "net/http"
  8. "net/smtp"
  9. "net/url"
  10. "strings"
  11. )
  12. func SendEmailBySMTP(user, host, port, pass, subject, email, content string, html bool) error {
  13. auth := smtp.PlainAuth("", user, pass, host)
  14. contentType := "Content-Type:text/plain;charset=UTF-8"
  15. if html {
  16. contentType = "Content-Type:text/html;charset=UTF-8"
  17. }
  18. msg := []byte("To: " + email + "\r\nFrom: " + user + ">\r\nSubject: " + subject + "\r\n" + contentType + "\r\n\r\n" + content)
  19. to := strings.Split(email, ";")
  20. return smtp.SendMail(strings.Join([]string{host, port}, ":"), auth, user, to, msg)
  21. }
  22. func SendEmailBySendCloud(uri, apiUser, apiKey, from, fromName, subject, email, content string, html bool) error {
  23. params := url.Values{
  24. "apiUser": strings.Split(apiUser, ";"),
  25. "apiKey": strings.Split(apiKey, ";"),
  26. "from": strings.Split(from, ";"),
  27. "fromName": strings.Split(fromName, ";"),
  28. "to": strings.Split(email, ";"), //to此时为地址列表
  29. "subject": []string{subject},
  30. }
  31. if html {
  32. params["html"] = []string{content}
  33. } else {
  34. params["plain"] = []string{content}
  35. }
  36. postBody := bytes.NewBufferString(params.Encode())
  37. respHandle, err := http.Post(uri, "application/x-www-form-urlencoded", postBody)
  38. if err != nil {
  39. return err
  40. }
  41. defer respHandle.Body.Close()
  42. bodyByte, err := ioutil.ReadAll(respHandle.Body)
  43. if err != nil {
  44. return err
  45. }
  46. // 返回数据格式
  47. //{
  48. // "result": true,
  49. // "statusCode": 200,
  50. // "message": "请求成功",
  51. // "info": {
  52. // "emailIdList": ["1530103894330_100557_12907_2084.sc-10_9_63_161-inbound0$15135172753@163.com"]
  53. // }
  54. //}
  55. resp := &struct {
  56. Result bool `json:"result"`
  57. StatusCode int `json:"statusCode"`
  58. Message string `json:"message"`
  59. Info struct {
  60. EmailIdList []string `json:"emailIdList"`
  61. } `json:"info"`
  62. }{}
  63. if err := json.Unmarshal(bodyByte, resp); err != nil {
  64. return err
  65. }
  66. if resp.Result == true && resp.StatusCode == http.StatusOK {
  67. return nil
  68. } else {
  69. return errors.New(" email send failed.")
  70. }
  71. }