email.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. for _, s := range strings.Split(s1, ",") {
  162. s = strings.TrimSpace(s)
  163. ret = append(ret, buildUser(s))
  164. }
  165. }
  166. return ret
  167. }
  168. func (e *Email) ForwardBuildBytes(ctx *context.Context, forwardAddress string) []byte {
  169. var b bytes.Buffer
  170. from := []*mail.Address{{e.From.Name, e.From.EmailAddress}}
  171. to := []*mail.Address{
  172. {
  173. Address: forwardAddress,
  174. },
  175. }
  176. // Create our mail header
  177. var h mail.Header
  178. h.SetDate(time.Now())
  179. h.SetAddressList("From", from)
  180. h.SetAddressList("To", to)
  181. h.SetText("Subject", e.Subject)
  182. h.SetMessageID(fmt.Sprintf("%d@%s", e.MessageId, config.Instance.Domain))
  183. if len(e.Cc) != 0 {
  184. cc := []*mail.Address{}
  185. for _, user := range e.Cc {
  186. cc = append(cc, &mail.Address{
  187. Name: user.Name,
  188. Address: user.EmailAddress,
  189. })
  190. }
  191. h.SetAddressList("Cc", cc)
  192. }
  193. // Create a new mail writer
  194. mw, err := mail.CreateWriter(&b, h)
  195. if err != nil {
  196. log.WithContext(ctx).Fatal(err)
  197. }
  198. // Create a text part
  199. tw, err := mw.CreateInline()
  200. if err != nil {
  201. log.WithContext(ctx).Fatal(err)
  202. }
  203. var th mail.InlineHeader
  204. th.Set("Content-Type", "text/plain")
  205. w, err := tw.CreatePart(th)
  206. if err != nil {
  207. log.Fatal(err)
  208. }
  209. io.WriteString(w, string(e.Text))
  210. w.Close()
  211. var html mail.InlineHeader
  212. html.Set("Content-Type", "text/html")
  213. w, err = tw.CreatePart(html)
  214. if err != nil {
  215. log.Fatal(err)
  216. }
  217. io.WriteString(w, string(e.HTML))
  218. w.Close()
  219. tw.Close()
  220. // Create an attachment
  221. for _, attachment := range e.Attachments {
  222. var ah mail.AttachmentHeader
  223. ah.Set("Content-Type", attachment.ContentType)
  224. ah.SetFilename(attachment.Filename)
  225. w, err = mw.CreateAttachment(ah)
  226. if err != nil {
  227. log.WithContext(ctx).Fatal(err)
  228. continue
  229. }
  230. w.Write(attachment.Content)
  231. w.Close()
  232. }
  233. mw.Close()
  234. // dkim 签名后返回
  235. return instance.Sign(b.String())
  236. }
  237. func (e *Email) BuildBytes(ctx *context.Context, dkim bool) []byte {
  238. var b bytes.Buffer
  239. from := []*mail.Address{{e.From.Name, e.From.EmailAddress}}
  240. to := []*mail.Address{}
  241. for _, user := range e.To {
  242. to = append(to, &mail.Address{
  243. Name: user.Name,
  244. Address: user.EmailAddress,
  245. })
  246. }
  247. // Create our mail header
  248. var h mail.Header
  249. if e.Date != "" {
  250. t, err := time.ParseInLocation("2006-01-02 15:04:05", e.Date, time.Local)
  251. if err != nil {
  252. log.WithContext(ctx).Errorf("Time Error ! Err:%+v", err)
  253. h.SetDate(time.Now())
  254. } else {
  255. h.SetDate(t)
  256. }
  257. } else {
  258. h.SetDate(time.Now())
  259. }
  260. h.SetMessageID(fmt.Sprintf("%d@%s", e.MessageId, config.Instance.Domain))
  261. h.SetAddressList("From", from)
  262. h.SetAddressList("To", to)
  263. h.SetText("Subject", e.Subject)
  264. if len(e.Cc) != 0 {
  265. cc := []*mail.Address{}
  266. for _, user := range e.Cc {
  267. cc = append(cc, &mail.Address{
  268. Name: user.Name,
  269. Address: user.EmailAddress,
  270. })
  271. }
  272. h.SetAddressList("Cc", cc)
  273. }
  274. // Create a new mail writer
  275. mw, err := mail.CreateWriter(&b, h)
  276. if err != nil {
  277. log.WithContext(ctx).Fatal(err)
  278. }
  279. // Create a text part
  280. tw, err := mw.CreateInline()
  281. if err != nil {
  282. log.WithContext(ctx).Fatal(err)
  283. }
  284. var th mail.InlineHeader
  285. th.SetContentType("text/plain", map[string]string{
  286. "charset": "UTF-8",
  287. })
  288. w, err := tw.CreatePart(th)
  289. if err != nil {
  290. log.Fatal(err)
  291. }
  292. io.WriteString(w, string(e.Text))
  293. w.Close()
  294. var html mail.InlineHeader
  295. html.SetContentType("text/html", map[string]string{
  296. "charset": "UTF-8",
  297. })
  298. w, err = tw.CreatePart(html)
  299. if err != nil {
  300. log.Fatal(err)
  301. }
  302. if len(e.HTML) > 0 {
  303. io.WriteString(w, string(e.HTML))
  304. } else {
  305. io.WriteString(w, string(e.Text))
  306. }
  307. w.Close()
  308. tw.Close()
  309. // Create an attachment
  310. for _, attachment := range e.Attachments {
  311. var ah mail.AttachmentHeader
  312. ah.Set("Content-Type", attachment.ContentType)
  313. ah.SetFilename(attachment.Filename)
  314. w, err = mw.CreateAttachment(ah)
  315. if err != nil {
  316. log.WithContext(ctx).Fatal(err)
  317. continue
  318. }
  319. w.Write(attachment.Content)
  320. w.Close()
  321. }
  322. mw.Close()
  323. if dkim {
  324. // dkim 签名后返回
  325. return instance.Sign(b.String())
  326. }
  327. return b.Bytes()
  328. }