messages.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. package email
  2. /*
  3. messages.go
  4. Listing and reading messages.
  5. Listing pages through a mailbox by sequence number when no filter applies
  6. (newest arrivals first, one FETCH per page) and through SEARCH / SORT
  7. results otherwise. Bodies are never downloaded for the list: the preview
  8. line comes from a ranged fetch of the first text part.
  9. Reading fetches the structure first and then only the parts the reading
  10. pane shows (text, HTML and inline images), so a message with a 20 MB
  11. attachment opens as fast as one without. Attachments are fetched on demand
  12. by their part number.
  13. */
  14. import (
  15. "bufio"
  16. "bytes"
  17. "context"
  18. "encoding/base64"
  19. "errors"
  20. "net/mail"
  21. "regexp"
  22. "sort"
  23. "strconv"
  24. "strings"
  25. "time"
  26. "github.com/emersion/go-imap/v2"
  27. "github.com/emersion/go-imap/v2/imapclient"
  28. gomessage "github.com/emersion/go-message"
  29. gomail "github.com/emersion/go-message/mail"
  30. "github.com/emersion/go-message/textproto"
  31. )
  32. const (
  33. maxPageSize = 200
  34. maxLocalSortWindow = 3000
  35. previewBytes = 3072
  36. maxInlineImage = 6 * 1024 * 1024
  37. maxInlineTotal = 24 * 1024 * 1024
  38. maxDisplayPart = 8 * 1024 * 1024
  39. maxRawMessage = 150 * 1024 * 1024
  40. )
  41. // ListQuery selects a page of a mailbox.
  42. type ListQuery struct {
  43. Folder string `json:"folder"`
  44. Page int `json:"page"`
  45. PageSize int `json:"pageSize"`
  46. Sort string `json:"sort"` //date | date_asc | from | subject | size
  47. Filter string `json:"filter"` //all | unread | flagged | attachments | unanswered
  48. Search string `json:"search"` //Free text
  49. SearchIn string `json:"searchIn"` //all | from | to | subject | body
  50. Previews bool `json:"previews"`
  51. }
  52. func (q *ListQuery) normalise() {
  53. if q.Folder == "" {
  54. q.Folder = "INBOX"
  55. }
  56. if q.Page < 0 {
  57. q.Page = 0
  58. }
  59. if q.PageSize <= 0 {
  60. q.PageSize = 50
  61. }
  62. if q.PageSize > maxPageSize {
  63. q.PageSize = maxPageSize
  64. }
  65. if !oneOf(q.Sort, "date", "date_asc", "from", "subject", "size") {
  66. q.Sort = "date"
  67. }
  68. if !oneOf(q.Filter, "all", "unread", "flagged", "attachments", "unanswered") {
  69. q.Filter = "all"
  70. }
  71. if !oneOf(q.SearchIn, "all", "from", "to", "subject", "body") {
  72. q.SearchIn = "all"
  73. }
  74. q.Search = strings.TrimSpace(q.Search)
  75. }
  76. // criteria builds the SEARCH criteria of a query, nil when everything matches.
  77. func (q *ListQuery) criteria() *imap.SearchCriteria {
  78. criteria := &imap.SearchCriteria{}
  79. used := false
  80. switch q.Filter {
  81. case "unread":
  82. criteria.NotFlag = append(criteria.NotFlag, imap.FlagSeen)
  83. used = true
  84. case "flagged":
  85. criteria.Flag = append(criteria.Flag, imap.FlagFlagged)
  86. used = true
  87. case "unanswered":
  88. criteria.NotFlag = append(criteria.NotFlag, imap.FlagAnswered)
  89. used = true
  90. case "attachments":
  91. //IMAP cannot search for attachments; mixed multipart is the standard
  92. //container for them and what other clients approximate with too
  93. criteria.Header = append(criteria.Header, imap.SearchCriteriaHeaderField{Key: "Content-Type", Value: "multipart/mixed"})
  94. used = true
  95. }
  96. if q.Search != "" {
  97. for _, word := range splitSearchTerms(q.Search) {
  98. switch q.SearchIn {
  99. case "from":
  100. criteria.Header = append(criteria.Header, imap.SearchCriteriaHeaderField{Key: "From", Value: word})
  101. case "to":
  102. criteria.Or = append(criteria.Or, [2]imap.SearchCriteria{
  103. {Header: []imap.SearchCriteriaHeaderField{{Key: "To", Value: word}}},
  104. {Header: []imap.SearchCriteriaHeaderField{{Key: "Cc", Value: word}}},
  105. })
  106. case "subject":
  107. criteria.Header = append(criteria.Header, imap.SearchCriteriaHeaderField{Key: "Subject", Value: word})
  108. case "body":
  109. criteria.Body = append(criteria.Body, word)
  110. default:
  111. criteria.Text = append(criteria.Text, word)
  112. }
  113. }
  114. used = true
  115. }
  116. if !used {
  117. return nil
  118. }
  119. return criteria
  120. }
  121. var quotedTermPattern = regexp.MustCompile(`"([^"]+)"|(\S+)`)
  122. // splitSearchTerms honours "quoted phrases" and drops very short noise.
  123. func splitSearchTerms(search string) []string {
  124. terms := []string{}
  125. for _, match := range quotedTermPattern.FindAllStringSubmatch(search, 8) {
  126. term := match[1]
  127. if term == "" {
  128. term = match[2]
  129. }
  130. term = strings.TrimSpace(term)
  131. if term != "" {
  132. terms = append(terms, term)
  133. }
  134. }
  135. return terms
  136. }
  137. var listFetchOptions = &imap.FetchOptions{
  138. UID: true,
  139. Flags: true,
  140. Envelope: true,
  141. InternalDate: true,
  142. RFC822Size: true,
  143. BodyStructure: &imap.FetchItemBodyStructure{Extended: true},
  144. BodySection: []*imap.FetchItemBodySection{{
  145. Specifier: imap.PartSpecifierHeader,
  146. HeaderFields: []string{"X-Priority", "Importance", "Priority"},
  147. Peek: true,
  148. }},
  149. }
  150. // ListMessages returns a page of a mailbox.
  151. func (m *Manager) ListMessages(ctx context.Context, p Principal, accountID string, query ListQuery) (*MessageList, error) {
  152. account, err := m.account(p, accountID)
  153. if err != nil {
  154. return nil, err
  155. }
  156. query.normalise()
  157. var result *MessageList
  158. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  159. var err error
  160. result, err = m.listMessages(c, p, account, query)
  161. return err
  162. })
  163. if err != nil {
  164. return nil, err
  165. }
  166. m.clearAuthError(p, account)
  167. m.applyLocalState(p, result.Messages)
  168. return result, nil
  169. }
  170. func selectFolder(c *imapclient.Client, folder string) (*imap.SelectData, error) {
  171. data, err := c.Select(folder, nil).Wait()
  172. if err != nil {
  173. var statusErr *imap.Error
  174. if errors.As(err, &statusErr) && (statusErr.Code == imap.ResponseCodeNonExistent ||
  175. strings.Contains(strings.ToLower(statusErr.Text), "doesn't exist") ||
  176. strings.Contains(strings.ToLower(statusErr.Text), "does not exist") ||
  177. strings.Contains(strings.ToLower(statusErr.Text), "unknown mailbox")) {
  178. return nil, ErrFolderNotFound
  179. }
  180. return nil, err
  181. }
  182. return data, nil
  183. }
  184. func (m *Manager) listMessages(c *imapclient.Client, p Principal, account *Account, query ListQuery) (*MessageList, error) {
  185. selected, err := selectFolder(c, query.Folder)
  186. if err != nil {
  187. return nil, err
  188. }
  189. result := &MessageList{Page: query.Page, PageSize: query.PageSize, Messages: []MessageSummary{}}
  190. criteria := query.criteria()
  191. total := selected.NumMessages
  192. var buffers []*imapclient.FetchMessageBuffer
  193. order := map[imap.UID]int{}
  194. if criteria == nil && (query.Sort == "date" || query.Sort == "date_asc") {
  195. //Fast path: sequence numbers follow arrival order
  196. result.Total = int(total)
  197. var start, stop uint32
  198. offset := uint32(query.Page * query.PageSize)
  199. if offset >= total {
  200. return result, nil
  201. }
  202. if query.Sort == "date" {
  203. stop = total - offset
  204. if stop > uint32(query.PageSize) {
  205. start = stop - uint32(query.PageSize) + 1
  206. } else {
  207. start = 1
  208. }
  209. } else {
  210. start = offset + 1
  211. stop = start + uint32(query.PageSize) - 1
  212. if stop > total {
  213. stop = total
  214. }
  215. }
  216. var seqSet imap.SeqSet
  217. seqSet.AddRange(start, stop)
  218. buffers, err = c.Fetch(seqSet, listFetchOptions).Collect()
  219. if err != nil {
  220. return nil, err
  221. }
  222. sort.Slice(buffers, func(i, j int) bool {
  223. if query.Sort == "date" {
  224. return buffers[i].SeqNum > buffers[j].SeqNum
  225. }
  226. return buffers[i].SeqNum < buffers[j].SeqNum
  227. })
  228. } else {
  229. uids, sortUnsupported, err := m.orderedUIDs(c, criteria, query)
  230. if err != nil {
  231. return nil, err
  232. }
  233. result.SortUnsupported = sortUnsupported
  234. result.Total = len(uids)
  235. begin := query.Page * query.PageSize
  236. if begin >= len(uids) {
  237. return result, nil
  238. }
  239. end := begin + query.PageSize
  240. if end > len(uids) {
  241. end = len(uids)
  242. }
  243. pageUIDs := uids[begin:end]
  244. for index, uid := range pageUIDs {
  245. order[uid] = index
  246. }
  247. buffers, err = c.Fetch(imap.UIDSetNum(pageUIDs...), listFetchOptions).Collect()
  248. if err != nil {
  249. return nil, err
  250. }
  251. sort.Slice(buffers, func(i, j int) bool { return order[buffers[i].UID] < order[buffers[j].UID] })
  252. }
  253. for _, buffer := range buffers {
  254. result.Messages = append(result.Messages, summaryFromBuffer(account.ID, query.Folder, selected.UIDValidity, buffer))
  255. }
  256. if query.Previews {
  257. m.fillPreviews(c, p.Username, account.ID, query.Folder, selected.UIDValidity, buffers, result.Messages)
  258. }
  259. return result, nil
  260. }
  261. // orderedUIDs runs SEARCH / SORT for a filtered or re-sorted listing.
  262. func (m *Manager) orderedUIDs(c *imapclient.Client, criteria *imap.SearchCriteria, query ListQuery) ([]imap.UID, bool, error) {
  263. searchCriteria := criteria
  264. if searchCriteria == nil {
  265. searchCriteria = &imap.SearchCriteria{}
  266. }
  267. sortKey := map[string]imapclient.SortKey{
  268. "date": imapclient.SortKeyArrival, "date_asc": imapclient.SortKeyArrival,
  269. "from": imapclient.SortKeyFrom, "subject": imapclient.SortKeySubject, "size": imapclient.SortKeySize,
  270. }[query.Sort]
  271. reverse := query.Sort == "date" || query.Sort == "size"
  272. if c.Caps().Has(imap.CapSort) {
  273. sortCommand := c.UIDSort(&imapclient.SortOptions{
  274. SearchCriteria: searchCriteria,
  275. SortCriteria: []imapclient.SortCriterion{{Key: sortKey, Reverse: reverse}},
  276. })
  277. if nums, err := sortCommand.Wait(); err == nil {
  278. uids := make([]imap.UID, len(nums))
  279. for i, num := range nums {
  280. uids[i] = imap.UID(num)
  281. }
  282. return uids, false, nil
  283. }
  284. //Fall through to SEARCH when SORT is advertised but fails
  285. }
  286. data, err := c.UIDSearch(searchCriteria, nil).Wait()
  287. if err != nil {
  288. return nil, false, err
  289. }
  290. uids := data.AllUIDs()
  291. sort.Slice(uids, func(i, j int) bool { return uids[i] < uids[j] })
  292. switch query.Sort {
  293. case "date":
  294. reverseUIDs(uids)
  295. return uids, false, nil
  296. case "date_asc":
  297. return uids, false, nil
  298. }
  299. //Sorting by sender / subject / size without server SORT means reading the
  300. //envelope of every match, which is only reasonable for small result sets
  301. if len(uids) > maxLocalSortWindow {
  302. reverseUIDs(uids)
  303. return uids, true, nil
  304. }
  305. if len(uids) == 0 {
  306. return uids, false, nil
  307. }
  308. buffers, err := c.Fetch(imap.UIDSetNum(uids...), &imap.FetchOptions{UID: true, Envelope: true, RFC822Size: true}).Collect()
  309. if err != nil {
  310. return nil, false, err
  311. }
  312. keyOf := func(buffer *imapclient.FetchMessageBuffer) string {
  313. if buffer.Envelope == nil {
  314. return ""
  315. }
  316. switch query.Sort {
  317. case "from":
  318. if len(buffer.Envelope.From) > 0 {
  319. from := buffer.Envelope.From[0]
  320. if from.Name != "" {
  321. return strings.ToLower(from.Name)
  322. }
  323. return strings.ToLower(from.Addr())
  324. }
  325. case "subject":
  326. return strings.ToLower(baseSubject(buffer.Envelope.Subject))
  327. }
  328. return ""
  329. }
  330. sort.SliceStable(buffers, func(i, j int) bool {
  331. if query.Sort == "size" {
  332. return buffers[i].RFC822Size > buffers[j].RFC822Size
  333. }
  334. return keyOf(buffers[i]) < keyOf(buffers[j])
  335. })
  336. sorted := make([]imap.UID, 0, len(buffers))
  337. for _, buffer := range buffers {
  338. sorted = append(sorted, buffer.UID)
  339. }
  340. return sorted, false, nil
  341. }
  342. func reverseUIDs(uids []imap.UID) {
  343. for i, j := 0, len(uids)-1; i < j; i, j = i+1, j-1 {
  344. uids[i], uids[j] = uids[j], uids[i]
  345. }
  346. }
  347. var subjectPrefixPattern = regexp.MustCompile(`(?i)^\s*((re|fw|fwd|aw|wg|sv|vs|antw|回复|回覆|答复|转发|轉寄)\s*(\[\d+\])?\s*[::]\s*)+`)
  348. // baseSubject strips reply / forward prefixes for sorting and threading.
  349. func baseSubject(subject string) string {
  350. return strings.TrimSpace(subjectPrefixPattern.ReplaceAllString(subject, ""))
  351. }
  352. // summaryFromBuffer converts a FETCH response into a list row.
  353. func summaryFromBuffer(accountID string, folder string, uidValidity uint32, buffer *imapclient.FetchMessageBuffer) MessageSummary {
  354. summary := MessageSummary{
  355. AccountID: accountID,
  356. Folder: folder,
  357. UID: uint32(buffer.UID),
  358. UIDValidity: uidValidity,
  359. Size: buffer.RFC822Size,
  360. Priority: 3,
  361. From: []Address{},
  362. To: []Address{},
  363. Cc: []Address{},
  364. Labels: []string{},
  365. }
  366. if !buffer.InternalDate.IsZero() {
  367. summary.Received = buffer.InternalDate.UnixMilli()
  368. }
  369. if envelope := buffer.Envelope; envelope != nil {
  370. summary.Subject = decodeHeaderWords(envelope.Subject)
  371. summary.MessageID = envelope.MessageID
  372. summary.From = convertAddresses(envelope.From)
  373. summary.To = convertAddresses(envelope.To)
  374. summary.Cc = convertAddresses(envelope.Cc)
  375. if !envelope.Date.IsZero() {
  376. summary.Date = envelope.Date.UnixMilli()
  377. }
  378. }
  379. if summary.Date == 0 {
  380. summary.Date = summary.Received
  381. }
  382. if summary.Received == 0 {
  383. summary.Received = summary.Date
  384. }
  385. applyFlags(&summary, buffer.Flags)
  386. if buffer.BodyStructure != nil {
  387. summary.HasAttachments = hasRealAttachments(treeFromBodyStructure(buffer.BodyStructure))
  388. }
  389. for _, section := range buffer.BodySection {
  390. if section.Section != nil && section.Section.Specifier == imap.PartSpecifierHeader {
  391. summary.Priority = priorityFromHeader(section.Bytes)
  392. }
  393. }
  394. return summary
  395. }
  396. func applyFlags(summary *MessageSummary, flags []imap.Flag) {
  397. for _, flag := range flags {
  398. switch strings.ToLower(string(flag)) {
  399. case strings.ToLower(string(imap.FlagSeen)):
  400. summary.Seen = true
  401. case strings.ToLower(string(imap.FlagFlagged)):
  402. summary.Flagged = true
  403. case strings.ToLower(string(imap.FlagAnswered)):
  404. summary.Answered = true
  405. case strings.ToLower(string(imap.FlagDraft)):
  406. summary.Draft = true
  407. case strings.ToLower(string(imap.FlagForwarded)):
  408. summary.Forwarded = true
  409. }
  410. }
  411. }
  412. func convertAddresses(list []imap.Address) []Address {
  413. results := []Address{}
  414. for _, address := range list {
  415. if address.IsGroupStart() || address.IsGroupEnd() {
  416. continue
  417. }
  418. email := address.Addr()
  419. if email == "" {
  420. continue
  421. }
  422. results = append(results, Address{Name: decodeHeaderWords(address.Name), Email: email})
  423. }
  424. return results
  425. }
  426. // priorityFromHeader reads X-Priority / Importance / Priority.
  427. func priorityFromHeader(raw []byte) int {
  428. header, err := textproto.ReadHeader(bufio.NewReader(bytes.NewReader(append(raw, '\r', '\n'))))
  429. if err != nil {
  430. return 3
  431. }
  432. return priorityFromFields(header.Get("X-Priority"), header.Get("Importance"), header.Get("Priority"))
  433. }
  434. func priorityFromFields(xPriority string, importance string, priority string) int {
  435. if value := strings.TrimSpace(xPriority); value != "" {
  436. if n, err := strconv.Atoi(value[:1]); err == nil && n >= 1 && n <= 5 {
  437. switch {
  438. case n <= 2:
  439. return 1
  440. case n >= 4:
  441. return 5
  442. }
  443. return 3
  444. }
  445. }
  446. switch strings.ToLower(strings.TrimSpace(importance)) {
  447. case "high":
  448. return 1
  449. case "low":
  450. return 5
  451. }
  452. switch strings.ToLower(strings.TrimSpace(priority)) {
  453. case "urgent":
  454. return 1
  455. case "non-urgent":
  456. return 5
  457. }
  458. return 3
  459. }
  460. // fillPreviews fetches the first bytes of each message's main text part.
  461. func (m *Manager) fillPreviews(c *imapclient.Client, owner string, accountID string, folder string, uidValidity uint32,
  462. buffers []*imapclient.FetchMessageBuffer, summaries []MessageSummary) {
  463. type wanted struct {
  464. index int
  465. part *mimePart
  466. html bool
  467. }
  468. groups := map[string][]wanted{}
  469. for index, buffer := range buffers {
  470. key := previewKey(owner, accountID, folder, uidValidity, uint32(buffer.UID))
  471. if cached, ok := m.previews.get(key); ok {
  472. summaries[index].Preview = cached
  473. continue
  474. }
  475. tree := treeFromBodyStructure(buffer.BodyStructure)
  476. parts := selectDisplayParts(tree)
  477. part, isHTML := parts.text, false
  478. if part == nil {
  479. part, isHTML = parts.html, true
  480. }
  481. if part == nil {
  482. m.previews.put(key, "")
  483. continue
  484. }
  485. groups[part.Path] = append(groups[part.Path], wanted{index: index, part: part, html: isHTML})
  486. }
  487. for path, items := range groups {
  488. uids := make([]imap.UID, 0, len(items))
  489. for _, item := range items {
  490. uids = append(uids, buffers[item.index].UID)
  491. }
  492. section := &imap.FetchItemBodySection{Part: partNumbers(path), Peek: true, Partial: &imap.SectionPartial{Offset: 0, Size: previewBytes}}
  493. fetched, err := c.Fetch(imap.UIDSetNum(uids...), &imap.FetchOptions{UID: true, BodySection: []*imap.FetchItemBodySection{section}}).Collect()
  494. if err != nil {
  495. continue
  496. }
  497. byUID := map[imap.UID][]byte{}
  498. for _, buffer := range fetched {
  499. for _, body := range buffer.BodySection {
  500. byUID[buffer.UID] = body.Bytes
  501. }
  502. }
  503. for _, item := range items {
  504. uid := buffers[item.index].UID
  505. raw, ok := byUID[uid]
  506. if !ok {
  507. continue
  508. }
  509. text := partText(item.part, raw, true)
  510. if item.html {
  511. text = htmlToText(text, false)
  512. }
  513. preview := previewText(text, 180)
  514. summaries[item.index].Preview = preview
  515. m.previews.put(previewKey(owner, accountID, folder, uidValidity, uint32(uid)), preview)
  516. }
  517. }
  518. }
  519. // partNumbers turns "1.2" into []int{1, 2}.
  520. func partNumbers(path string) []int {
  521. if path == "" {
  522. return nil
  523. }
  524. fields := strings.Split(path, ".")
  525. numbers := make([]int, 0, len(fields))
  526. for _, field := range fields {
  527. n, err := strconv.Atoi(field)
  528. if err != nil {
  529. return nil
  530. }
  531. numbers = append(numbers, n)
  532. }
  533. return numbers
  534. }
  535. // GetOptions controls GetMessage.
  536. type GetOptions struct {
  537. MarkSeen bool `json:"markSeen"`
  538. AllowRemote bool `json:"allowRemote"`
  539. }
  540. // GetMessage loads one message for the reading pane.
  541. func (m *Manager) GetMessage(ctx context.Context, p Principal, accountID string, folder string, uid uint32, options GetOptions) (*Message, error) {
  542. account, err := m.account(p, accountID)
  543. if err != nil {
  544. return nil, err
  545. }
  546. settings := m.store.getSettings(p.Username)
  547. var message *Message
  548. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  549. selected, err := selectFolder(c, folder)
  550. if err != nil {
  551. return err
  552. }
  553. uidSet := imap.UIDSetNum(imap.UID(uid))
  554. headerSection := &imap.FetchItemBodySection{Specifier: imap.PartSpecifierHeader, Peek: true}
  555. buffers, err := c.Fetch(uidSet, &imap.FetchOptions{
  556. UID: true, Flags: true, Envelope: true, InternalDate: true, RFC822Size: true,
  557. BodyStructure: &imap.FetchItemBodyStructure{Extended: true},
  558. BodySection: []*imap.FetchItemBodySection{headerSection},
  559. }).Collect()
  560. if err != nil {
  561. return err
  562. }
  563. if len(buffers) == 0 {
  564. return ErrMessageNotFound
  565. }
  566. buffer := buffers[0]
  567. summary := summaryFromBuffer(account.ID, folder, selected.UIDValidity, buffer)
  568. header := parseHeaderBytes(buffer.FindBodySection(headerSection))
  569. tree := treeFromBodyStructure(buffer.BodyStructure)
  570. parts := selectDisplayParts(tree)
  571. bodies := map[string][]byte{}
  572. needed := []*mimePart{}
  573. if parts.html != nil && parts.html.Size <= maxDisplayPart {
  574. needed = append(needed, parts.html)
  575. }
  576. if parts.text != nil && parts.text.Size <= maxDisplayPart {
  577. needed = append(needed, parts.text)
  578. }
  579. inlineBudget := int64(maxInlineTotal)
  580. for _, part := range parts.inline {
  581. if part.Size <= maxInlineImage && part.Size <= inlineBudget {
  582. needed = append(needed, part)
  583. inlineBudget -= part.Size
  584. }
  585. }
  586. if len(needed) > 0 {
  587. sections := []*imap.FetchItemBodySection{}
  588. for _, part := range needed {
  589. sections = append(sections, &imap.FetchItemBodySection{Part: partNumbers(part.Path), Peek: true})
  590. }
  591. fetched, err := c.Fetch(uidSet, &imap.FetchOptions{UID: true, BodySection: sections}).Collect()
  592. if err != nil {
  593. return err
  594. }
  595. if len(fetched) > 0 {
  596. for i, part := range needed {
  597. bodies[part.Path] = fetched[0].FindBodySection(sections[i])
  598. }
  599. }
  600. }
  601. //A broken BODYSTRUCTURE (it happens) leaves nothing to show: parse the
  602. //whole message locally instead when it is of a sane size
  603. if parts.html == nil && parts.text == nil && buffer.RFC822Size > 0 && buffer.RFC822Size <= 32*1024*1024 {
  604. fullSection := &imap.FetchItemBodySection{Peek: true}
  605. full, err := c.Fetch(uidSet, &imap.FetchOptions{UID: true, BodySection: []*imap.FetchItemBodySection{fullSection}}).Collect()
  606. if err == nil && len(full) > 0 {
  607. if entity, perr := gomessage.Read(bytes.NewReader(full[0].FindBodySection(fullSection))); perr == nil || gomessage.IsUnknownCharset(perr) {
  608. tree = treeFromEntity(entity)
  609. parts = selectDisplayParts(tree)
  610. bodies = map[string][]byte{}
  611. }
  612. }
  613. }
  614. allowRemote := options.AllowRemote || settings.RemoteImages == "always"
  615. if !allowRemote && len(summary.From) > 0 && settings.IsTrustedSender(summary.From[0].Email) {
  616. allowRemote = true
  617. }
  618. message = buildMessage(summary, header, parts, bodies, allowRemote)
  619. if options.MarkSeen && !summary.Seen {
  620. if err := c.Store(uidSet, &imap.StoreFlags{Op: imap.StoreFlagsAdd, Silent: true, Flags: []imap.Flag{imap.FlagSeen}}, nil).Close(); err == nil {
  621. message.Seen = true
  622. }
  623. }
  624. return nil
  625. })
  626. if err != nil {
  627. return nil, err
  628. }
  629. m.clearAuthError(p, account)
  630. summaries := []MessageSummary{message.MessageSummary}
  631. m.applyLocalState(p, summaries)
  632. message.Labels = summaries[0].Labels
  633. return message, nil
  634. }
  635. // parseHeaderBytes parses a raw header block, tolerating junk.
  636. func parseHeaderBytes(raw []byte) gomail.Header {
  637. if len(raw) == 0 {
  638. return gomail.Header{}
  639. }
  640. header, err := textproto.ReadHeader(bufio.NewReader(bytes.NewReader(raw)))
  641. if err != nil {
  642. return gomail.Header{Header: gomessage.Header{Header: header}}
  643. }
  644. return gomail.Header{Header: gomessage.Header{Header: header}}
  645. }
  646. // buildMessage assembles the reading-pane message from fetched parts.
  647. func buildMessage(summary MessageSummary, header gomail.Header, parts displayParts, bodies map[string][]byte, allowRemote bool) *Message {
  648. message := &Message{
  649. MessageSummary: summary,
  650. ReplyTo: headerAddresses(header, "Reply-To"),
  651. Bcc: headerAddresses(header, "Bcc"),
  652. References: []string{},
  653. Attachments: attachmentInfo(parts.attachments),
  654. Signed: parts.signed,
  655. Encrypted: parts.encrypted,
  656. Calendar: parts.calendar,
  657. RemoteAllowed: allowRemote,
  658. }
  659. if summary.Subject == "" {
  660. if subject, err := header.Subject(); err == nil {
  661. message.Subject = subject
  662. }
  663. }
  664. if ids, err := header.MsgIDList("In-Reply-To"); err == nil && len(ids) > 0 {
  665. message.InReplyTo = ids[0]
  666. }
  667. if ids, err := header.MsgIDList("References"); err == nil {
  668. message.References = ids
  669. }
  670. if message.MessageID == "" {
  671. if id, err := header.MessageID(); err == nil {
  672. message.MessageID = id
  673. }
  674. }
  675. if len(message.From) == 0 {
  676. message.From = headerAddresses(header, "From")
  677. }
  678. message.ListUnsubscribe = pickUnsubscribe(header.Get("List-Unsubscribe"))
  679. if receipt := headerAddresses(header, "Disposition-Notification-To"); len(receipt) > 0 {
  680. message.ReadReceiptTo = receipt[0].Email
  681. }
  682. message.Auth = parseAuthResults(header.Values("Authentication-Results"))
  683. if message.Priority == 3 {
  684. message.Priority = priorityFromFields(header.Get("X-Priority"), header.Get("Importance"), header.Get("Priority"))
  685. }
  686. if parts.text != nil {
  687. text := partText(parts.text, bodies[parts.text.Path], false)
  688. if strings.EqualFold(parts.text.Params["format"], "flowed") {
  689. text = unflowText(text, strings.EqualFold(parts.text.Params["delsp"], "yes"))
  690. }
  691. message.Text = text
  692. }
  693. if parts.html != nil {
  694. cid := map[string]string{}
  695. for _, part := range parts.inline {
  696. data := part.body
  697. if data == nil {
  698. raw, ok := bodies[part.Path]
  699. if !ok {
  700. continue
  701. }
  702. data = decodeTransfer(raw, part.Encoding, false)
  703. }
  704. cid[strings.ToLower(part.ContentID)] = "data:" + part.mediaType() + ";base64," + base64.StdEncoding.EncodeToString(data)
  705. }
  706. source := partText(parts.html, bodies[parts.html.Path], false)
  707. sanitized := sanitizeHTML(source, sanitizeOptions{allowRemote: allowRemote, cid: cid})
  708. message.HTML = sanitized.html
  709. message.HasRemoteContent = sanitized.hasRemote
  710. if message.Text == "" {
  711. message.Text = htmlToText(source, true)
  712. }
  713. }
  714. if message.Preview == "" {
  715. message.Preview = previewText(message.Text, 180)
  716. }
  717. return message
  718. }
  719. func headerAddresses(header gomail.Header, key string) []Address {
  720. results := []Address{}
  721. list, err := header.AddressList(key)
  722. if err != nil {
  723. //Fall back to a lenient split for malformed lists
  724. for _, piece := range strings.Split(header.Get(key), ",") {
  725. if parsed, perr := mail.ParseAddress(strings.TrimSpace(piece)); perr == nil {
  726. results = append(results, Address{Name: parsed.Name, Email: parsed.Address})
  727. }
  728. }
  729. return results
  730. }
  731. for _, address := range list {
  732. results = append(results, Address{Name: address.Name, Email: address.Address})
  733. }
  734. return results
  735. }
  736. // pickUnsubscribe prefers an https unsubscribe link over mailto.
  737. func pickUnsubscribe(header string) string {
  738. if header == "" {
  739. return ""
  740. }
  741. var mailto string
  742. for _, item := range strings.Split(header, ",") {
  743. item = strings.Trim(strings.TrimSpace(item), "<>")
  744. lower := strings.ToLower(item)
  745. if strings.HasPrefix(lower, "https://") || strings.HasPrefix(lower, "http://") {
  746. return item
  747. }
  748. if strings.HasPrefix(lower, "mailto:") && mailto == "" {
  749. mailto = item
  750. }
  751. }
  752. return mailto
  753. }
  754. var authResultPattern = regexp.MustCompile(`(?i)\b(spf|dkim|dmarc)\s*=\s*([a-z]+)`)
  755. // parseAuthResults keeps the verdicts of the first (receiving) server.
  756. func parseAuthResults(values []string) *AuthResults {
  757. if len(values) == 0 {
  758. return nil
  759. }
  760. results := &AuthResults{}
  761. for _, match := range authResultPattern.FindAllStringSubmatch(values[0], -1) {
  762. verdict := strings.ToLower(match[2])
  763. switch strings.ToLower(match[1]) {
  764. case "spf":
  765. if results.SPF == "" {
  766. results.SPF = verdict
  767. }
  768. case "dkim":
  769. if results.DKIM == "" || verdict == "pass" {
  770. results.DKIM = verdict
  771. }
  772. case "dmarc":
  773. if results.DMARC == "" {
  774. results.DMARC = verdict
  775. }
  776. }
  777. }
  778. if results.SPF == "" && results.DKIM == "" && results.DMARC == "" {
  779. return nil
  780. }
  781. return results
  782. }
  783. // unflowText reverses format=flowed soft line breaks (RFC 3676).
  784. func unflowText(text string, delSpace bool) string {
  785. lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n")
  786. var builder strings.Builder
  787. for i, line := range lines {
  788. if line == "-- " {
  789. builder.WriteString(line + "\n")
  790. continue
  791. }
  792. if strings.HasPrefix(line, " ") {
  793. line = line[1:] //Space stuffing
  794. }
  795. if strings.HasSuffix(line, " ") && i < len(lines)-1 {
  796. if delSpace {
  797. line = strings.TrimSuffix(line, " ")
  798. }
  799. builder.WriteString(line)
  800. continue
  801. }
  802. builder.WriteString(line)
  803. if i < len(lines)-1 {
  804. builder.WriteString("\n")
  805. }
  806. }
  807. return builder.String()
  808. }
  809. // GetRaw downloads the full RFC 822 source of a message.
  810. func (m *Manager) GetRaw(ctx context.Context, p Principal, accountID string, folder string, uid uint32) (*RawMessage, error) {
  811. account, err := m.account(p, accountID)
  812. if err != nil {
  813. return nil, err
  814. }
  815. var raw *RawMessage
  816. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  817. if _, err := selectFolder(c, folder); err != nil {
  818. return err
  819. }
  820. section := &imap.FetchItemBodySection{Peek: true}
  821. buffers, err := c.Fetch(imap.UIDSetNum(imap.UID(uid)), &imap.FetchOptions{
  822. UID: true, Envelope: true, InternalDate: true, RFC822Size: true, BodySection: []*imap.FetchItemBodySection{section},
  823. }).Collect()
  824. if err != nil {
  825. return err
  826. }
  827. if len(buffers) == 0 {
  828. return ErrMessageNotFound
  829. }
  830. if buffers[0].RFC822Size > maxRawMessage {
  831. return ErrTooLarge
  832. }
  833. subject := ""
  834. if buffers[0].Envelope != nil {
  835. subject = decodeHeaderWords(buffers[0].Envelope.Subject)
  836. }
  837. raw = &RawMessage{Filename: emlFilename(subject, buffers[0].InternalDate), Data: buffers[0].FindBodySection(section)}
  838. return nil
  839. })
  840. return raw, err
  841. }
  842. // emlFilename names a saved message after its subject.
  843. func emlFilename(subject string, date time.Time) string {
  844. name := strings.TrimSpace(subject)
  845. if name == "" {
  846. name = "Message"
  847. }
  848. if len([]rune(name)) > 80 {
  849. name = string([]rune(name)[:80])
  850. }
  851. if !date.IsZero() {
  852. name = date.Format("2006-01-02") + " " + name
  853. }
  854. return sanitizeFilename(name) + ".eml"
  855. }
  856. // GetPart downloads one attachment by its part number.
  857. func (m *Manager) GetPart(ctx context.Context, p Principal, accountID string, folder string, uid uint32, partID string) (*PartData, error) {
  858. account, err := m.account(p, accountID)
  859. if err != nil {
  860. return nil, err
  861. }
  862. numbers := partNumbers(partID)
  863. if numbers == nil {
  864. return nil, errors.New("invalid attachment id")
  865. }
  866. var data *PartData
  867. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  868. if _, err := selectFolder(c, folder); err != nil {
  869. return err
  870. }
  871. uidSet := imap.UIDSetNum(imap.UID(uid))
  872. structure, err := c.Fetch(uidSet, &imap.FetchOptions{UID: true, BodyStructure: &imap.FetchItemBodyStructure{Extended: true}}).Collect()
  873. if err != nil {
  874. return err
  875. }
  876. if len(structure) == 0 {
  877. return ErrMessageNotFound
  878. }
  879. tree := treeFromBodyStructure(structure[0].BodyStructure)
  880. part := tree.find(partID)
  881. if part == nil {
  882. return errors.New("attachment not found")
  883. }
  884. section := &imap.FetchItemBodySection{Part: numbers, Peek: true}
  885. buffers, err := c.Fetch(uidSet, &imap.FetchOptions{UID: true, BodySection: []*imap.FetchItemBodySection{section}}).Collect()
  886. if err != nil {
  887. return err
  888. }
  889. if len(buffers) == 0 {
  890. return ErrMessageNotFound
  891. }
  892. info := attachmentInfo([]*mimePart{part})[0]
  893. data = &PartData{
  894. Filename: info.Filename,
  895. ContentType: part.mediaType(),
  896. Data: decodeTransfer(buffers[0].FindBodySection(section), part.Encoding, false),
  897. }
  898. return nil
  899. })
  900. return data, err
  901. }