| 1 |
// Package main extracts attachments from the provided email |
| 2 |
package main |
| 3 |
|
| 4 |
import ( |
| 5 |
"flag" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
"io/ioutil" |
| 9 |
"os" |
| 10 |
"path/filepath" |
| 11 |
|
| 12 |
"github.com/jhillyerd/enmime" |
| 13 |
"github.com/jhillyerd/enmime/cmd" |
| 14 |
) |
| 15 |
|
| 16 |
var ( |
| 17 |
mimefile = flag.String("f", "", "mime(eml) file") |
| 18 |
outdir = flag.String("o", "", "output dir") |
| 19 |
) |
| 20 |
|
| 21 |
type extractor struct { |
| 22 |
errOut, stdOut io.Writer |
| 23 |
exit exitFunc |
| 24 |
wd workingDir |
| 25 |
fileWrite attachmentWriter |
| 26 |
} |
| 27 |
|
| 28 |
type exitFunc func(int) |
| 29 |
type workingDir func() (string, error) |
| 30 |
type attachmentWriter func(string, []byte, os.FileMode) error |
| 31 |
|
| 32 |
func newDefaultExtractor() *extractor { |
| 33 |
return &extractor{ |
| 34 |
errOut: os.Stderr, |
| 35 |
stdOut: os.Stdout, |
| 36 |
exit: os.Exit, |
| 37 |
wd: os.Getwd, |
| 38 |
fileWrite: ioutil.WriteFile, |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
func main() { |
| 43 |
flag.Parse() |
| 44 |
ex := newDefaultExtractor() |
| 45 |
ex.exit(ex.extract(*mimefile, *outdir)) |
| 46 |
} |
| 47 |
|
| 48 |
func (ex *extractor) extract(file, dir string) int { |
| 49 |
if file == "" { |
| 50 |
fmt.Fprintln(ex.errOut, "Missing filename argument") |
| 51 |
flag.Usage() |
| 52 |
return 1 |
| 53 |
} |
| 54 |
if dir == "" { |
| 55 |
dir, _ = ex.wd() |
| 56 |
} |
| 57 |
|
| 58 |
if err := os.MkdirAll(dir, os.ModePerm); err != nil { |
| 59 |
fmt.Fprintf(ex.errOut, "Mkdir %s failed.", dir) |
| 60 |
return 2 |
| 61 |
} |
| 62 |
|
| 63 |
reader, err := os.Open(file) |
| 64 |
if err != nil { |
| 65 |
fmt.Fprintln(ex.errOut, "Failed to open file:", err) |
| 66 |
return 1 |
| 67 |
} |
| 68 |
|
| 69 |
// basename is used as the markdown title |
| 70 |
basename := filepath.Base(file) |
| 71 |
e, err := enmime.ReadEnvelope(reader) |
| 72 |
if err != nil { |
| 73 |
fmt.Fprintln(ex.errOut, "During enmime.ReadEnvelope:", err) |
| 74 |
return 1 |
| 75 |
} |
| 76 |
|
| 77 |
if err = cmd.EnvelopeToMarkdown(ex.stdOut, e, basename); err != nil { |
| 78 |
fmt.Fprintln(ex.errOut, err) |
| 79 |
return 1 |
| 80 |
} |
| 81 |
|
| 82 |
// Write errOut attachments |
| 83 |
fmt.Fprintf(ex.errOut, "\nExtracting attachments into %s...", dir) |
| 84 |
for _, a := range e.Attachments { |
| 85 |
newFileName := filepath.Join(dir, a.FileName) |
| 86 |
err = ex.fileWrite(newFileName, a.Content, 0644) |
| 87 |
if err != nil { |
| 88 |
fmt.Fprintf(ex.stdOut, "Error writing file %q: %v\n", newFileName, err) |
| 89 |
break |
| 90 |
} |
| 91 |
} |
| 92 |
fmt.Fprintln(ex.errOut, " Done!") |
| 93 |
return 0 |
| 94 |
} |