Source file email_simple.ml
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
open Core.Core_stable
module Stable = struct
module Content = struct
module V1 = Email.Stable.V1
end
module Mimetype = struct
module V1 = struct
type t = String.V1.t [@@deriving bin_io, compare, sexp]
end
end
end
open! Core
open Poly
let ?normalize t name = Headers.last ?normalize (Email.headers t) name
let t =
Email.modify_headers t ~f:(fun -> Headers.add_all headers headers')
;;
let t ~name ~value =
Email.modify_headers t ~f:(Headers.set_at_bottom ~name ~value)
;;
module Expert = struct
let content ~ ~ ~encoding body =
let =
[ ( "Content-Transfer-Encoding"
, Octet_stream.Encoding.to_string (encoding :> Octet_stream.Encoding.t) )
]
@ extra_headers
in
let = Headers.of_list ~normalize:normalize_headers headers in
let octet_stream =
body |> Bigstring_shared.of_string |> Octet_stream.encode ~encoding
in
Email_content.to_email ~headers (Data octet_stream)
;;
let multipart ~ ~content_type ~ parts =
let multipart = Email_content.Multipart.create parts in
let = [ "Content-Type", content_type ] @ extra_headers in
let = Headers.of_list ~normalize:normalize_headers headers in
Email_content.to_email ~headers (Multipart multipart)
;;
let create_raw
~from
~to_
?(cc = [])
?reply_to
~subject
~id
?in_reply_to
~date
?auto_generated
?( = [])
?(attachments = [])
content
=
let id, =
let =
List.Assoc.find extra_headers "Message-Id" ~equal:String.Caseless.equal
in
let () =
List.Assoc.remove extra_headers "Message-Id" ~equal:String.Caseless.equal
in
match id_from_extra_headers with
| None -> id, extra_headers
| Some id' ->
if String.equal (String.strip id) (String.strip id')
then id, remove_id_from_extra_headers ()
else
id, extra_headers
in
let =
extra_headers
@ [ "From", from ]
@ (if List.is_empty to_ then [] else [ "To", String.concat to_ ~sep:",\n " ])
@ (if List.is_empty cc then [] else [ "Cc", String.concat cc ~sep:",\n " ])
@ (match reply_to with
| None -> []
| Some reply_to -> [ "Reply-To", reply_to ])
@ [ "Subject", subject ]
@ [ "Message-Id", id ]
@ (match in_reply_to with
| None -> []
| Some in_reply_to -> [ "In-Reply-To", in_reply_to ])
@ (match auto_generated with
| None -> []
| Some () -> [ "Auto-Submitted", "auto-generated"; "Precedence", "bulk" ])
@ [ "Date", date ]
in
match attachments with
| [] -> add_headers content headers
| attachments ->
multipart
~normalize_headers:`Whitespace
~content_type:"multipart/mixed"
~extra_headers:headers
(set_header_at_bottom content ~name:"Content-Disposition" ~value:"inline"
:: List.map attachments ~f:(fun (name, content) ->
let content_type =
last_header content "Content-Type"
|> Option.value ~default:"application/x-octet-stream"
in
set_header_at_bottom
content
~name:"Content-Type"
~value:(sprintf "%s; name=%s" content_type (Mimestring.quote name))
|> set_header_at_bottom
~name:"Content-Disposition"
~value:(sprintf "attachment; filename=%s" (Mimestring.quote name))))
;;
end
module Mimetype = struct
type t = Stable.Mimetype.V1.t [@@deriving compare, sexp_of]
let text = "text/plain"
let text_utf8 = "text/plain; charset=\"UTF-8\""
let html = "text/html"
let html_utf8 = "text/html; charset=\"UTF-8\""
let pdf = "application/pdf"
let jpg = "image/jpeg"
let png = "image/png"
let csv = "text/csv"
let multipart_mixed = "multipart/mixed"
let multipart_alternative = "multipart/alternative"
let multipart_related = "multipart/related"
let of_string t = t
let equal = [%compare.equal: t]
let arg_type = Command.Arg_type.create of_string
let from_extension ext = Magic_mime_external.Mime_types.map_extension ext
let from_filename file = Magic_mime_external.Magic_mime.lookup file
let to_extension t =
match
String.lsplit2 t ~on:';'
|> Option.value_map ~f:fst ~default:t
|> String.lowercase
|> String.strip
with
| "text/plain" -> Some "txt"
| "text/html" -> Some "html"
| "application/pdf" -> Some "pdf"
| "image/jpeg" -> Some "jpg"
| "image/png" -> Some "png"
| "image/gif" -> Some "gif"
| "text/csv" -> Some "csv"
| "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" -> Some "xlsx"
| "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ->
Some "docx"
| _ -> None
;;
let guess_encoding : t -> Octet_stream.Encoding.known = function
| "text/plain" | "text/html" -> `Quoted_printable
| _ -> `Base64
;;
end
type attachment_name = string [@@deriving sexp_of]
module Content = struct
type t = Email.t [@@deriving sexp_of]
let of_email = Fn.id
let create_custom
~content_type
?(encoding = Mimetype.guess_encoding content_type)
?( = [])
content
=
Expert.content
~normalize_headers:`Whitespace
~extra_headers:(extra_headers @ [ "Content-Type", content_type ])
~encoding
content
;;
let create = create_custom
let html_utf8 ?(encoding = `Quoted_printable) ? content =
create ?extra_headers ~content_type:Mimetype.html_utf8 ~encoding content
;;
let text_utf8 ?(encoding = `Quoted_printable) ? content =
create ?extra_headers ~content_type:Mimetype.text_utf8 ~encoding content
;;
let create_multipart ?( = []) ~content_type = function
| [] -> failwith "at least one part is required"
| [ content ] -> add_headers content extra_headers
| parts ->
Expert.multipart ~normalize_headers:`Whitespace ~content_type ~extra_headers parts
;;
let alternatives ? =
create_multipart ?extra_headers ~content_type:Mimetype.multipart_alternative
;;
let html_pre ?(force_no_line_wrap = true) str =
let html_encode s =
let escape =
[ "&", "&"; "<", "<"; ">", ">"; "\"", """; "'", "'" ]
in
List.fold ~init:s escape ~f:(fun acc (pattern, with_) ->
String.substr_replace_all acc ~pattern ~with_)
in
let pre content =
let open_tag =
if force_no_line_wrap
then
"<pre style=\"white-space: pre !important;\">"
else "<pre>"
in
let close_tag = "</pre>" in
[%string "%{open_tag}%{content}%{close_tag}"]
in
"<html>" ^ pre (html_encode str) ^ "</html>"
;;
let text_monospace_utf8 ? ?force_no_line_wrap content =
alternatives
?extra_headers
[ text_utf8 ?encoding:None content
; html_utf8 ?encoding:None (html_pre ?force_no_line_wrap content)
]
;;
let mixed ? =
create_multipart ?extra_headers ~content_type:Mimetype.multipart_mixed
;;
let with_related ?( = []) ~resources t =
Expert.multipart
~normalize_headers:`Whitespace
~content_type:Mimetype.multipart_related
~extra_headers
(add_headers t [ "Content-Disposition", "inline" ]
:: List.map resources ~f:(fun (name, content) ->
add_headers content [ "Content-Id", sprintf "<%s>" name ]))
;;
let t name =
match last_header t name with
| None -> None
| Some str ->
(match String.split str ~on:';' |> List.map ~f:String.strip with
| [] -> None
| v :: args ->
let args =
List.map args ~f:(fun str ->
match String.lsplit2 str ~on:'=' with
| None -> str, None
| Some (k, v) -> String.strip k, Some (String.strip v))
in
Some (v, args))
;;
let content_type t =
let open Option.Let_syntax in
parse_last_header t "Content-Type"
>>| fst
|> Option.value ~default:"application/x-octet-stream"
;;
let strip_character_set_and_language filename =
match
String.substr_index filename ~pattern:"'" ~pos:1
|> Option.bind ~f:(fun pos ->
String.substr_index filename ~pattern:"'" ~pos:(pos + 1))
|> Option.map ~f:(fun pos -> pos + 1)
with
| Some pos -> String.subo filename ~pos
| None -> filename
;;
let unquote name =
let len = String.length name in
if len >= 2 && name.[0] = '"' && name.[len - 1] = '"'
then String.sub name ~pos:1 ~len:(len - 2)
else name
;;
let handle_value_continuation ~all_parameters ~attribute_name =
let matching_attributes =
List.filter
all_parameters
~f:(fun (fragment_attribute, (_ : attachment_name option)) ->
String.Caseless.is_prefix fragment_attribute ~prefix:(attribute_name ^ "*"))
|> Nonempty_list.of_list_exn
in
match matching_attributes with
| [ (_, maybe_value) ] ->
Option.value maybe_value ~default:"" |> unquote |> strip_character_set_and_language
| _ :: _ as matching_attributes ->
let matching_attributes =
Nonempty_list.to_list matching_attributes
|> List.map ~f:(fun (fragment_attribute, value) ->
match String.split fragment_attribute ~on:'*' with
| _ :: digit :: _ when String.for_all digit ~f:Char.is_digit ->
let digit = Int.of_string digit in
Ok (digit, value)
| _ -> Error "multipart-fragment-construction-failed")
|> Result.all
in
(match matching_attributes with
| Error error -> error
| Ok all_parameters ->
List.sort all_parameters ~compare:(fun a b ->
Comparable.lift Int.compare ~f:fst a b)
|> List.map ~f:(fun (seq, name_fragment) ->
let name_fragment = unquote (Option.value name_fragment ~default:"") in
if seq = 0
then
strip_character_set_and_language name_fragment
else name_fragment)
|> String.concat ~sep:"")
;;
let attachment_name_from_args args ~attribute_name =
List.find_map args ~f:(fun (k, v) ->
if String.Caseless.equal k attribute_name
then Option.map ~f:unquote v
else if
String.Caseless.is_prefix k ~prefix:(attribute_name ^ "*")
then Some (handle_value_continuation ~all_parameters:args ~attribute_name)
else None)
;;
let attachment_name t =
let open Option.Let_syntax in
Option.first_some
(let%bind disp, args = parse_last_header t "Content-Disposition" in
if String.Caseless.equal disp "attachment"
then attachment_name_from_args args ~attribute_name:"filename"
else None)
(let%bind _, args = parse_last_header t "Content-Type" in
attachment_name_from_args args ~attribute_name:"name")
;;
let related_part_cid t =
let open Option.Let_syntax in
let%map str = last_header t "Content-Id" >>| String.strip in
String.chop_prefix str ~prefix:"<"
>>= String.chop_suffix ~suffix:">"
|> Option.value ~default:str
;;
let content_disposition t =
match parse_last_header t "Content-Disposition" with
| None -> `Inline
| Some (disp, _) ->
if String.Caseless.equal disp "inline"
then `Inline
else if String.Caseless.equal disp "attachment"
then `Attachment (attachment_name t |> Option.value ~default:"unnamed-attachment")
else (
match attachment_name t with
| None -> `Inline
| Some name -> `Attachment name)
;;
let parts t =
match Email_content.parse t with
| Error _ -> None
| Ok (Email_content.Multipart ts) -> Some ts.Email_content.Multipart.parts
| Ok (Message _) -> None
| Ok (Data _) -> None
;;
let content t =
match Email_content.parse t with
| Error _ -> None
| Ok (Email_content.Multipart _) -> None
| Ok (Message _) -> None
| Ok (Data data) -> Some data
;;
let rec inline_parts t =
match parts t with
| Some parts ->
if String.Caseless.equal (content_type t) Mimetype.multipart_alternative
then
[ t ]
else List.concat_map parts ~f:inline_parts
| None ->
(match content_disposition t with
| `Inline -> [ t ]
| `Attachment _ -> [])
;;
let rec alternative_parts t =
match parts t with
| None -> [ t ]
| Some ts ->
if String.Caseless.equal (content_type t) Mimetype.multipart_alternative
then List.concat_map ts ~f:alternative_parts
else [ t ]
;;
let rec all_related_parts t =
let get_cid t =
Option.map (related_part_cid t) ~f:(fun cid -> [ cid, t ])
|> Option.value ~default:[]
in
get_cid t
@ (parts t |> Option.value ~default:[] |> List.concat_map ~f:all_related_parts)
;;
let find_related t name =
List.find (all_related_parts t) ~f:(fun (cid, _t) -> String.equal cid name)
|> Option.map ~f:snd
;;
let text ?(encoding = `Quoted_printable) ? content =
create ?extra_headers ~content_type:Mimetype.text ~encoding content
;;
let html ?(encoding = `Quoted_printable) ? content =
create ?extra_headers ~content_type:Mimetype.html ~encoding content
;;
let text_monospace ? ?force_no_line_wrap content =
alternatives
?extra_headers
[ text ?encoding:None content
; html ?encoding:None (html_pre ?force_no_line_wrap content)
]
;;
end
type t = Email.t [@@deriving sexp_of]
let create
~from
~to_
?cc
?reply_to
~subject
~id
?in_reply_to
~date_string
?auto_generated
?
?attachments
content
=
Expert.create_raw
~from:(Email_address.to_string from)
~to_:(List.map to_ ~f:Email_address.to_string)
?cc:(Option.map cc ~f:(List.map ~f:Email_address.to_string))
?reply_to:(Option.map reply_to ~f:Email_address.to_string)
~subject
~id
?in_reply_to
~date:date_string
?auto_generated
?extra_headers
?attachments
content
;;
let ?normalize name ~f t =
Option.bind (last_header ?normalize t name) ~f:(fun v ->
Option.try_with (fun () -> f v))
;;
let from = decode_last_header "From" ~f:Email_address.of_string_exn
let to_ = decode_last_header "To" ~f:Email_address.list_of_string_exn
let cc = decode_last_header "Cc" ~f:Email_address.list_of_string_exn
let subject =
decode_last_header ~normalize:`Whitespace_and_encoded_words "Subject" ~f:Fn.id
;;
let id = decode_last_header "Message-Id" ~f:Fn.id
let rec extract_body_ext'
~(accept : (Mimetype.t * (string * string option) list) option -> 'format option)
email
: ('format * string) Sequence.t
=
match accept (Content.parse_last_header email "Content-Type") with
| Some format ->
(match
Octet_stream.of_bigstring_shared
~encoding:(Octet_stream.Encoding.of_headers_or_default (Email.headers email))
(Email.raw_content email |> Email_raw_content.to_bigstring_shared)
|> Octet_stream.decode
with
| Some body -> Sequence.singleton (format, Bigstring_shared.to_string body)
| None -> Sequence.empty)
| None ->
(match Email_content.parse email with
| Ok (Multipart parts) ->
Sequence.of_list parts.parts |> Sequence.concat_map ~f:(extract_body_ext' ~accept)
| Error _ | Ok (Message _) | Ok (Data _) ->
Sequence.empty)
;;
let extract_body_ext ~accept ?order t =
let parts = extract_body_ext' ~accept t in
match order with
| None -> Sequence.hd parts
| Some order -> Sequence.min_elt parts ~compare:(Comparable.lift order ~f:fst)
;;
let extract_body ?(content_type = Mimetype.text) email =
extract_body_ext
~accept:(function
| None -> None
| Some (type_, _) -> Option.some_if (String.Caseless.equal type_ content_type) ())
email
|> Option.map ~f:snd
;;
let all_related_parts = Content.all_related_parts
let find_related = Content.find_related
let inline_parts = Content.inline_parts