email.go 8.0 KB

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