/
mime-extractor.go
76 lines (67 loc) · 1.61 KB
/
mime-extractor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Package main extracts attachments from the provided email
package main
import (
"flag"
"fmt"
"io"
"os"
"path"
"github.com/jhillyerd/enmime"
"github.com/jhillyerd/enmime/cmd"
)
var (
mimefile = flag.String("f", "", "mime(eml) file")
outdir = flag.String("o", "", "output dir")
)
func main() {
flag.Parse()
if *mimefile == "" {
fmt.Fprintln(os.Stderr, "Missing filename argument")
flag.Usage()
os.Exit(1)
}
cwd, _ := os.Getwd()
if *outdir == "" {
outdir = &cwd
}
if err := os.MkdirAll(*outdir, os.ModePerm); err != nil {
fmt.Fprintf(os.Stderr, "Mkdir %s failed.", *outdir)
os.Exit(2)
}
reader, err := os.Open(*mimefile)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to open file:", err)
os.Exit(1)
}
// basename is used as the markdown title
basename := path.Base(*mimefile)
e, err := enmime.ReadEnvelope(reader)
if err != nil {
fmt.Fprintln(os.Stderr, "During enmime.ReadEnvelope:", err)
os.Exit(1)
}
if err = cmd.EnvelopeToMarkdown(os.Stdout, e, basename); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// Write out attachments
fmt.Fprintf(os.Stderr, "\nExtracting attachments into %s...", *outdir)
for _, a := range e.Attachments {
newFileName := path.Join(*outdir, a.FileName)
f, err := os.Create(newFileName)
if err != nil {
fmt.Printf("Error creating file %q: %v\n", newFileName, err)
break
}
_, err = io.Copy(f, a)
if err != nil {
fmt.Printf("Error writing file %q: %v\n", newFileName, err)
break
}
if f.Close() != nil {
fmt.Printf("Error closing file %q: %v\n", newFileName, err)
break
}
}
fmt.Fprintln(os.Stderr, " Done!")
}