email.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. package parsemail
  2. import (
  3. "bytes"
  4. "github.com/emersion/go-message"
  5. _ "github.com/emersion/go-message/charset"
  6. "github.com/emersion/go-message/mail"
  7. log "github.com/sirupsen/logrus"
  8. "github.com/spf13/cast"
  9. "io"
  10. "net/textproto"
  11. "pmail/utils/array"
  12. "pmail/utils/context"
  13. "regexp"
  14. "strings"
  15. "time"
  16. )
  17. type User struct {
  18. EmailAddress string `json:"EmailAddress"`
  19. Name string `json:"Name"`
  20. }
  21. func (u User) GetDomainAccount() (string, string) {
  22. infos := strings.Split(u.EmailAddress, "@")
  23. if len(infos) >= 2 {
  24. return infos[0], infos[1]
  25. }
  26. return "", ""
  27. }
  28. type Attachment struct {
  29. Filename string
  30. ContentType string
  31. Content []byte
  32. ContentID string
  33. }
  34. // Email is the type used for email messages
  35. type Email struct {
  36. ReplyTo []*User
  37. From *User
  38. To []*User
  39. Bcc []*User
  40. Cc []*User
  41. Subject string
  42. Text []byte // Plaintext message (optional)
  43. HTML []byte // Html message (optional)
  44. Sender *User // override From as SMTP envelope sender (optional)
  45. Headers textproto.MIMEHeader
  46. Attachments []*Attachment
  47. ReadReceipt []string
  48. Date string
  49. IsRead int
  50. Status int // 0未发送,1已发送,2发送失败,3删除
  51. GroupId int // 分组id
  52. MessageId int64
  53. }
  54. func NewEmailFromReader(to []string, r io.Reader) *Email {
  55. ret := &Email{}
  56. m, err := message.Read(r)
  57. if err != nil {
  58. log.Errorf("email解析错误! Error %+v", err)
  59. }
  60. ret.From = buildUser(m.Header.Get("From"))
  61. if len(to) > 0 {
  62. ret.To = buildUsers(to)
  63. } else {
  64. ret.To = buildUsers(m.Header.Values("To"))
  65. }
  66. ret.Cc = buildUsers(m.Header.Values("Cc"))
  67. ret.ReplyTo = buildUsers(m.Header.Values("ReplyTo"))
  68. ret.Sender = buildUser(m.Header.Get("Sender"))
  69. if ret.Sender == nil {
  70. ret.Sender = ret.From
  71. }
  72. ret.Subject, _ = m.Header.Text("Subject")
  73. sendTime, err := time.Parse(time.RFC1123Z, m.Header.Get("Date"))
  74. if err != nil {
  75. sendTime = time.Now()
  76. }
  77. ret.Date = sendTime.Format(time.DateTime)
  78. m.Walk(func(path []int, entity *message.Entity, err error) error {
  79. return formatContent(entity, ret)
  80. })
  81. return ret
  82. }
  83. func formatContent(entity *message.Entity, ret *Email) error {
  84. contentType, p, err := entity.Header.ContentType()
  85. if err != nil {
  86. log.Errorf("email read error! %+v", err)
  87. return err
  88. }
  89. switch contentType {
  90. case "multipart/alternative":
  91. case "multipart/mixed":
  92. case "text/plain":
  93. ret.Text, _ = io.ReadAll(entity.Body)
  94. case "text/html":
  95. ret.HTML, _ = io.ReadAll(entity.Body)
  96. case "multipart/related":
  97. entity.Walk(func(path []int, entity *message.Entity, err error) error {
  98. if t, _, _ := entity.Header.ContentType(); t == "multipart/related" {
  99. return nil
  100. }
  101. return formatContent(entity, ret)
  102. })
  103. default:
  104. c, _ := io.ReadAll(entity.Body)
  105. fileName := p["name"]
  106. if fileName == "" {
  107. contentDisposition := entity.Header.Get("Content-Disposition")
  108. r := regexp.MustCompile("filename=(.*)")
  109. matchs := r.FindStringSubmatch(contentDisposition)
  110. if len(matchs) == 2 {
  111. fileName = matchs[1]
  112. } else {
  113. fileName = "no_name_file"
  114. }
  115. }
  116. ret.Attachments = append(ret.Attachments, &Attachment{
  117. Filename: fileName,
  118. ContentType: contentType,
  119. Content: c,
  120. ContentID: strings.TrimPrefix(strings.TrimSuffix(entity.Header.Get("Content-Id"), ">"), "<"),
  121. })
  122. }
  123. return nil
  124. }
  125. func BuilderUser(str string) *User {
  126. return buildUser(str)
  127. }
  128. func buildUser(str string) *User {
  129. if str == "" {
  130. return nil
  131. }
  132. ret := &User{}
  133. args := strings.Split(str, " ")
  134. if len(args) == 1 {
  135. ret.EmailAddress = str
  136. return ret
  137. }
  138. if len(args) > 2 {
  139. targs := []string{
  140. array.Join(args[0:len(args)-1], " "),
  141. args[len(args)-1],
  142. }
  143. args = targs
  144. }
  145. args[0] = strings.Trim(args[0], "\"")
  146. args[1] = strings.TrimPrefix(args[1], "<")
  147. args[1] = strings.TrimSuffix(args[1], ">")
  148. name, err := (&WordDecoder{}).Decode(strings.ReplaceAll(args[0], "\"", ""))
  149. if err == nil {
  150. ret.Name = name
  151. } else {
  152. ret.Name = args[0]
  153. }
  154. ret.EmailAddress = args[1]
  155. return ret
  156. }
  157. func buildUsers(str []string) []*User {
  158. var ret []*User
  159. for _, s1 := range str {
  160. for _, s := range strings.Split(s1, ",") {
  161. s = strings.TrimSpace(s)
  162. ret = append(ret, buildUser(s))
  163. }
  164. }
  165. return ret
  166. }
  167. func (e *Email) ForwardBuildBytes(ctx *context.Context, forwardAddress string) []byte {
  168. var b bytes.Buffer
  169. from := []*mail.Address{{e.From.Name, e.From.EmailAddress}}
  170. to := []*mail.Address{
  171. {
  172. Address: forwardAddress,
  173. },
  174. }
  175. // Create our mail header
  176. var h mail.Header
  177. h.SetDate(time.Now())
  178. h.SetAddressList("From", from)
  179. h.SetAddressList("To", to)
  180. h.SetText("Subject", e.Subject)
  181. h.SetMessageID(cast.ToString(e.MessageId))
  182. if len(e.Cc) != 0 {
  183. cc := []*mail.Address{}
  184. for _, user := range e.Cc {
  185. cc = append(cc, &mail.Address{
  186. Name: user.Name,
  187. Address: user.EmailAddress,
  188. })
  189. }
  190. h.SetAddressList("Cc", cc)
  191. }
  192. // Create a new mail writer
  193. mw, err := mail.CreateWriter(&b, h)
  194. if err != nil {
  195. log.WithContext(ctx).Fatal(err)
  196. }
  197. // Create a text part
  198. tw, err := mw.CreateInline()
  199. if err != nil {
  200. log.WithContext(ctx).Fatal(err)
  201. }
  202. var th mail.InlineHeader
  203. th.Set("Content-Type", "text/plain")
  204. w, err := tw.CreatePart(th)
  205. if err != nil {
  206. log.Fatal(err)
  207. }
  208. io.WriteString(w, string(e.Text))
  209. w.Close()
  210. var html mail.InlineHeader
  211. html.Set("Content-Type", "text/html")
  212. w, err = tw.CreatePart(html)
  213. if err != nil {
  214. log.Fatal(err)
  215. }
  216. io.WriteString(w, string(e.HTML))
  217. w.Close()
  218. tw.Close()
  219. // Create an attachment
  220. for _, attachment := range e.Attachments {
  221. var ah mail.AttachmentHeader
  222. ah.Set("Content-Type", attachment.ContentType)
  223. ah.SetFilename(attachment.Filename)
  224. w, err = mw.CreateAttachment(ah)
  225. if err != nil {
  226. log.WithContext(ctx).Fatal(err)
  227. continue
  228. }
  229. w.Write(attachment.Content)
  230. w.Close()
  231. }
  232. mw.Close()
  233. // dkim 签名后返回
  234. return instance.Sign(b.String())
  235. }
  236. func (e *Email) BuildBytes(ctx *context.Context, dkim bool) []byte {
  237. var b bytes.Buffer
  238. from := []*mail.Address{{e.From.Name, e.From.EmailAddress}}
  239. to := []*mail.Address{}
  240. for _, user := range e.To {
  241. to = append(to, &mail.Address{
  242. Name: user.Name,
  243. Address: user.EmailAddress,
  244. })
  245. }
  246. // Create our mail header
  247. var h mail.Header
  248. if e.Date != "" {
  249. t, err := time.ParseInLocation("2006-01-02 15:04:05", e.Date, time.Local)
  250. if err != nil {
  251. log.WithContext(ctx).Errorf("Time Error ! Err:%+v", err)
  252. h.SetDate(time.Now())
  253. } else {
  254. h.SetDate(t)
  255. }
  256. } else {
  257. h.SetDate(time.Now())
  258. }
  259. h.SetMessageID(cast.ToString(e.MessageId))
  260. h.SetAddressList("From", from)
  261. h.SetAddressList("To", to)
  262. h.SetText("Subject", e.Subject)
  263. if len(e.Cc) != 0 {
  264. cc := []*mail.Address{}
  265. for _, user := range e.Cc {
  266. cc = append(cc, &mail.Address{
  267. Name: user.Name,
  268. Address: user.EmailAddress,
  269. })
  270. }
  271. h.SetAddressList("Cc", cc)
  272. }
  273. // Create a new mail writer
  274. mw, err := mail.CreateWriter(&b, h)
  275. if err != nil {
  276. log.WithContext(ctx).Fatal(err)
  277. }
  278. // Create a text part
  279. tw, err := mw.CreateInline()
  280. if err != nil {
  281. log.WithContext(ctx).Fatal(err)
  282. }
  283. var th mail.InlineHeader
  284. th.SetContentType("text/plain", map[string]string{
  285. "charset": "UTF-8",
  286. })
  287. w, err := tw.CreatePart(th)
  288. if err != nil {
  289. log.Fatal(err)
  290. }
  291. io.WriteString(w, string(e.Text))
  292. w.Close()
  293. var html mail.InlineHeader
  294. html.SetContentType("text/html", map[string]string{
  295. "charset": "UTF-8",
  296. })
  297. w, err = tw.CreatePart(html)
  298. if err != nil {
  299. log.Fatal(err)
  300. }
  301. if len(e.HTML) > 0 {
  302. io.WriteString(w, string(e.HTML))
  303. } else {
  304. io.WriteString(w, string(e.Text))
  305. }
  306. w.Close()
  307. tw.Close()
  308. // Create an attachment
  309. for _, attachment := range e.Attachments {
  310. var ah mail.AttachmentHeader
  311. ah.Set("Content-Type", attachment.ContentType)
  312. ah.SetFilename(attachment.Filename)
  313. w, err = mw.CreateAttachment(ah)
  314. if err != nil {
  315. log.WithContext(ctx).Fatal(err)
  316. continue
  317. }
  318. w.Write(attachment.Content)
  319. w.Close()
  320. }
  321. mw.Close()
  322. if dkim {
  323. // dkim 签名后返回
  324. return instance.Sign(b.String())
  325. }
  326. return b.Bytes()
  327. }