13 "github.com/mjl-/mox/mlog"
14 "github.com/mjl-/mox/store"
17// Export is used by webmail and webaccount to export messages of one or
18// multiple mailboxes, in maildir or mbox format, in a tar/tgz/zip archive or
20func Export(log mlog.Log, accName string, w http.ResponseWriter, r *http.Request) {
21 if r.Method != "POST" {
22 http.Error(w, "405 - method not allowed - use post", http.StatusMethodNotAllowed)
26 mailbox := r.FormValue("mailbox") // Empty means all.
27 format := r.FormValue("format")
28 archive := r.FormValue("archive")
29 recursive := r.FormValue("recursive") != ""
31 case "maildir", "mbox":
33 http.Error(w, "400 - bad request - unknown format", http.StatusBadRequest)
37 case "none", "tar", "tgz", "zip":
39 http.Error(w, "400 - bad request - unknown archive", http.StatusBadRequest)
42 if archive == "none" && (format != "mbox" || recursive) {
43 http.Error(w, "400 - bad request - archive none can only be used with non-recursive mbox", http.StatusBadRequest)
47 acc, err := store.OpenAccount(log, accName)
49 log.Errorx("open account for export", err)
50 http.Error(w, "500 - internal server error", http.StatusInternalServerError)
55 log.Check(err, "closing account")
58 name := strings.ReplaceAll(mailbox, "/", "-")
62 filename := fmt.Sprintf("mailexport-%s-%s", name, time.Now().Format("20060102-150405"))
63 filename += "." + format
64 var archiver store.Archiver
65 if archive == "none" {
66 w.Header().Set("Content-Type", "application/mbox")
67 archiver = &store.MboxArchiver{Writer: w}
68 } else if archive == "tar" {
69 // Don't tempt browsers to "helpfully" decompress.
70 w.Header().Set("Content-Type", "application/x-tar")
71 archiver = store.TarArchiver{Writer: tar.NewWriter(w)}
73 } else if archive == "tgz" {
74 // Don't tempt browsers to "helpfully" decompress.
75 w.Header().Set("Content-Type", "application/octet-stream")
77 gzw := gzip.NewWriter(w)
81 archiver = store.TarArchiver{Writer: tar.NewWriter(gzw)}
84 w.Header().Set("Content-Type", "application/zip")
85 archiver = store.ZipArchiver{Writer: zip.NewWriter(w)}
89 err := archiver.Close()
90 log.Check(err, "exporting mail close")
92 w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": filename}))
93 if err := store.ExportMessages(r.Context(), log, acc.DB, acc.Dir, archiver, format == "maildir", mailbox, recursive); err != nil {
94 log.Errorx("exporting mail", err)