send.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. package email
  2. /*
  3. send.go
  4. Sending and drafts.
  5. Send renders the message once. With no delay it is delivered right away;
  6. with an undo delay or a schedule it goes to the outbox, which delivers it
  7. from the server even if the browser is closed in the meantime.
  8. After delivery: a copy goes to the Sent folder unless the provider files
  9. sent mail itself (Gmail, Outlook), the original is flagged answered or
  10. forwarded, the draft it came from is removed and the recipients are
  11. remembered for address completion.
  12. */
  13. import (
  14. "context"
  15. "errors"
  16. "strings"
  17. "time"
  18. "github.com/emersion/go-imap/v2"
  19. "github.com/emersion/go-imap/v2/imapclient"
  20. "imuslab.com/arozos/mod/info/logger"
  21. )
  22. // SendResult reports what Send did.
  23. type SendResult struct {
  24. Queued bool `json:"queued"`
  25. OutboxID string `json:"outboxId,omitempty"`
  26. SendAt int64 `json:"sendAt,omitempty"`
  27. MessageID string `json:"messageId"`
  28. Warning string `json:"warning,omitempty"`
  29. }
  30. var draftFlags = []imap.Flag{imap.FlagDraft, imap.FlagSeen}
  31. // DraftResult identifies a saved draft. Attachments lists the draft's parts
  32. // so the composer can keep referring to them (by part id) once the files it
  33. // uploaded are embedded in the draft.
  34. type DraftResult struct {
  35. Folder string `json:"folder"`
  36. UID uint32 `json:"uid"`
  37. Attachments []Attachment `json:"attachments"`
  38. }
  39. // postSend describes the follow-up work of a delivered message.
  40. type postSend struct {
  41. SaveSent bool `json:"saveSent"`
  42. BccHeader string `json:"bccHeader,omitempty"`
  43. ReplyMode string `json:"replyMode,omitempty"`
  44. OriginalFolder string `json:"originalFolder,omitempty"`
  45. OriginalUID uint32 `json:"originalUid,omitempty"`
  46. DraftFolder string `json:"draftFolder,omitempty"`
  47. DraftUID uint32 `json:"draftUid,omitempty"`
  48. Recipients []Address `json:"recipients,omitempty"`
  49. }
  50. // shouldSaveSent applies the account's Sent-copy policy.
  51. func shouldSaveSent(account *Account) bool {
  52. switch account.SaveSent {
  53. case "always":
  54. return true
  55. case "never":
  56. return false
  57. }
  58. provider := account.Provider
  59. if provider == "custom" || provider == "" {
  60. if detected := providerForServer(account.SMTP.Host); detected != "" {
  61. provider = detected
  62. }
  63. }
  64. return presetSavesSent(provider)
  65. }
  66. // Send delivers (or queues) a message.
  67. func (m *Manager) Send(ctx context.Context, p Principal, request *ComposeRequest) (*SendResult, error) {
  68. account, err := m.account(p, request.AccountID)
  69. if err != nil {
  70. return nil, err
  71. }
  72. built, err := m.buildMessage(ctx, p, account, request, false)
  73. if err != nil {
  74. return nil, err
  75. }
  76. post := postSend{
  77. SaveSent: shouldSaveSent(account),
  78. BccHeader: built.bccHeader,
  79. ReplyMode: request.ReplyMode,
  80. OriginalFolder: request.OriginalFolder,
  81. OriginalUID: request.OriginalUID,
  82. DraftFolder: request.DraftFolder,
  83. DraftUID: request.DraftUID,
  84. Recipients: recipientAddresses(request),
  85. }
  86. sendAt := time.Time{}
  87. if request.SendAt > 0 {
  88. sendAt = time.UnixMilli(request.SendAt)
  89. }
  90. if request.UndoSeconds > 0 {
  91. undoAt := m.now().Add(time.Duration(request.UndoSeconds) * time.Second)
  92. if sendAt.Before(undoAt) {
  93. sendAt = undoAt
  94. }
  95. }
  96. if !sendAt.IsZero() && sendAt.After(m.now().Add(time.Second)) {
  97. item, err := m.outbox.enqueue(p, account, built, post, sendAt, request.Subject, request.To)
  98. if err != nil {
  99. return nil, err
  100. }
  101. return &SendResult{Queued: true, OutboxID: item.ID, SendAt: item.SendAt, MessageID: built.messageID}, nil
  102. }
  103. if err := m.sendRaw(ctx, p, account, built.from, built.recipients, built.raw); err != nil {
  104. m.noteAuthError(p, account, err)
  105. return nil, err
  106. }
  107. warning := m.afterDelivery(ctx, p, account, built.raw, built.messageID, built.date, post)
  108. return &SendResult{MessageID: built.messageID, Warning: warning}, nil
  109. }
  110. func recipientAddresses(request *ComposeRequest) []Address {
  111. results := []Address{}
  112. for _, list := range [][]string{request.To, request.Cc, request.Bcc} {
  113. parsed, err := parseRecipients(list)
  114. if err != nil {
  115. continue
  116. }
  117. for _, address := range parsed {
  118. results = append(results, Address{Name: address.Name, Email: address.Address})
  119. }
  120. }
  121. return results
  122. }
  123. // afterDelivery runs the follow-up work. Failures here never undo a sent
  124. // message, they are returned as a warning.
  125. func (m *Manager) afterDelivery(ctx context.Context, p Principal, account *Account, raw []byte, messageID string, date time.Time, post postSend) string {
  126. warnings := []string{}
  127. key := poolKey(p.Username, account.ID)
  128. err := m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  129. if post.SaveSent {
  130. sent, err := m.ensureRoleFolder(c, key, RoleSent)
  131. if err == nil {
  132. copyRaw := raw
  133. if post.BccHeader != "" {
  134. copyRaw = append([]byte(post.BccHeader), raw...)
  135. }
  136. _, err = appendMessage(c, sent, copyRaw, []imap.Flag{imap.FlagSeen}, date, "")
  137. }
  138. if err != nil {
  139. warnings = append(warnings, "the message was sent but could not be saved to the Sent folder: "+err.Error())
  140. }
  141. }
  142. if post.OriginalUID != 0 && post.OriginalFolder != "" {
  143. flag := imap.FlagAnswered
  144. if post.ReplyMode == "forward" {
  145. flag = imap.FlagForwarded
  146. }
  147. if _, err := selectFolder(c, post.OriginalFolder); err == nil {
  148. c.Store(imap.UIDSetNum(imap.UID(post.OriginalUID)), &imap.StoreFlags{Op: imap.StoreFlagsAdd, Silent: true, Flags: []imap.Flag{flag}}, nil).Close()
  149. }
  150. }
  151. if post.DraftUID != 0 && post.DraftFolder != "" {
  152. if _, err := selectFolder(c, post.DraftFolder); err == nil {
  153. expungeUIDs(c, imap.UIDSetNum(imap.UID(post.DraftUID)))
  154. }
  155. }
  156. return nil
  157. })
  158. if err != nil {
  159. warnings = append(warnings, "the message was sent, but the mailbox could not be updated: "+err.Error())
  160. }
  161. if m.store.getSettings(p.Username).AutoCollectContacts {
  162. m.collectContacts(p, post.Recipients)
  163. }
  164. if len(warnings) > 0 {
  165. logger.PrintAndLog("Email", "Post-send step failed for "+account.Email+": "+strings.Join(warnings, "; "), nil)
  166. }
  167. return strings.Join(warnings, "; ")
  168. }
  169. // SaveDraft stores the composer content in the Drafts folder, replacing the
  170. // previous version of the same draft.
  171. func (m *Manager) SaveDraft(ctx context.Context, p Principal, request *ComposeRequest) (*DraftResult, error) {
  172. account, err := m.account(p, request.AccountID)
  173. if err != nil {
  174. return nil, err
  175. }
  176. built, err := m.buildMessage(ctx, p, account, request, true)
  177. if err != nil {
  178. return nil, err
  179. }
  180. key := poolKey(p.Username, account.ID)
  181. result := &DraftResult{}
  182. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  183. drafts, err := m.ensureRoleFolder(c, key, RoleDrafts)
  184. if err != nil {
  185. return err
  186. }
  187. uid, err := appendMessage(c, drafts, built.raw, draftFlags, built.date, built.messageID)
  188. if err != nil {
  189. return err
  190. }
  191. result.Folder = drafts
  192. result.UID = uid
  193. result.Attachments = []Attachment{}
  194. if uid != 0 {
  195. if _, err := selectFolder(c, drafts); err == nil {
  196. structure, err := c.Fetch(imap.UIDSetNum(imap.UID(uid)), &imap.FetchOptions{UID: true, BodyStructure: &imap.FetchItemBodyStructure{Extended: true}}).Collect()
  197. if err == nil && len(structure) > 0 {
  198. parts := selectDisplayParts(treeFromBodyStructure(structure[0].BodyStructure))
  199. for _, attachment := range attachmentInfo(parts.attachments) {
  200. if !attachment.Inline {
  201. result.Attachments = append(result.Attachments, attachment)
  202. }
  203. }
  204. }
  205. }
  206. }
  207. //Drop the previous version once the new one is safely stored
  208. if request.DraftUID != 0 && request.DraftUID != uid {
  209. previousFolder := request.DraftFolder
  210. if previousFolder == "" {
  211. previousFolder = drafts
  212. }
  213. if _, err := selectFolder(c, previousFolder); err == nil {
  214. expungeUIDs(c, imap.UIDSetNum(imap.UID(request.DraftUID)))
  215. }
  216. }
  217. return nil
  218. })
  219. if err != nil {
  220. return nil, err
  221. }
  222. return result, nil
  223. }
  224. // DeleteDraft removes a draft the user discarded.
  225. func (m *Manager) DeleteDraft(ctx context.Context, p Principal, accountID string, folder string, uid uint32) error {
  226. if uid == 0 || folder == "" {
  227. return errors.New("no draft to delete")
  228. }
  229. account, err := m.account(p, accountID)
  230. if err != nil {
  231. return err
  232. }
  233. return m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  234. if _, err := selectFolder(c, folder); err != nil {
  235. return err
  236. }
  237. return expungeUIDs(c, imap.UIDSetNum(imap.UID(uid)))
  238. })
  239. }