-
Notifications
You must be signed in to change notification settings - Fork 128
/
email.d
1682 lines (1405 loc) · 46.1 KB
/
email.d
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/++
Create MIME emails with things like HTML, attachments, and send with convenience wrappers around std.net.curl's SMTP function, or read email from an mbox file.
For preparing and sending outgoing email, see [EmailMessage]. For processing incoming email or opening .eml files, mbox files, etc., see [IncomingEmailMessage].
History:
Originally released as open source on August 11, 2012. The last-modified date of its predecessor file was January 2011.
Many of the public string members were overhauled on May 13, 2024. Compatibility methods are provided so your code will hopefully still work, but this also results in some stricter adherence to email encoding rules, so you should retest if you update after then.
Future_Directions:
I might merge `IncomingEmailMessage` and `EmailMessage` some day, it seems silly to have them completely separate like this.
+/
module arsd.email;
import std.net.curl;
pragma(lib, "curl");
import std.base64;
import std.string;
import std.range;
import std.utf;
import std.array;
import std.algorithm.iteration;
import arsd.characterencodings;
// import std.uuid;
// smtpMessageBoundary = randomUUID().toString();
// SEE ALSO: std.net.curl.SMTP
/++
Credentials for a SMTP relay, as passed to [std.net.curl.SMTP].
+/
struct RelayInfo {
/++
Should be as a url, such as `smtp://example.com` or `smtps://example.com`. You normally want smtp:// - even if you want TLS encryption, smtp uses STARTTLS so it gets that. smtps will only work if the server supports tls from the start, which is not always the case.
+/
string server;
string username; ///
string password; ///
}
/++
Representation of an email attachment.
+/
struct MimeAttachment {
string type; /// e.g. `text/plain`
string filename; ///
const(ubyte)[] content; ///
string id; ///
}
///
enum ToType {
to,
cc,
bcc
}
/++
Structured representation of email users, including the name and email address as separate components.
`EmailRecipient` represents a single user, and `RecipientList` represents multiple users. A "recipient" may also be a from or reply to address.
`RecipientList` is a wrapper over `EmailRecipient[]` that provides overloads that take string arguments, for compatibility for users of previous versions of the `arsd.email` api. It should generally work as you expect if you just pretend it is a normal array though (and if it doesn't, you can get the internal array via the `recipients` member.)
History:
Added May 13, 2024 (dub v12.0) to replace the old plain, public strings and arrays of strings.
+/
struct EmailRecipient {
/++
The email user's name. It should not have quotes or any other encoding.
For example, `Adam D. Ruppe`.
+/
string name;
/++
The email address. It should not have brackets or any other encoding.
For example, `[email protected]`.
+/
string address;
/++
Returns a string representing this email address, in a format suitable for inclusion in a message about to be saved or transmitted.
In many cases, this is easy to read for people too, but not in all cases.
+/
string toProtocolString(string linesep = "\r\n") {
if(name.length)
return "\"" ~ encodeEmailHeaderContentForTransmit(name, linesep) ~ "\" <" ~ address ~ ">";
return address;
}
/++
Returns a string representing this email address, in a format suitable for being read by people. This is not necessarily reversible.
+/
string toReadableString() {
if(name.length)
return "\"" ~ name ~ "\" <" ~ address ~ ">";
return address;
}
/++
Construct an `EmailRecipient` either from a name and address (preferred!) or from an encoded string as found in an email header.
Examples:
`EmailRecipient("Adam D. Ruppe", "[email protected]")` or `EmailRecipient(`"Adam D. Ruppe" <[email protected]>`);
+/
this(string name, string address) {
this.name = name;
this.address = address;
}
/// ditto
this(string str) {
this = str;
}
/++
Provided for compatibility for users of old versions of `arsd.email` - does implicit conversion from `EmailRecipient` to a plain string (in protocol format), as was present in previous versions of the api.
+/
alias toProtocolString this;
/// ditto
void opAssign(string str) {
auto idx = str.indexOf("<");
if(idx == -1) {
name = null;
address = str;
} else {
name = decodeEncodedWord(unquote(str[0 .. idx].strip));
address = str[idx + 1 .. $ - 1];
}
}
}
/// ditto
struct RecipientList {
EmailRecipient[] recipients;
void opAssign(string[] strings) {
recipients = null;
foreach(s; strings)
recipients ~= EmailRecipient(s);
}
void opAssign(EmailRecipient[] recpts) {
this.recipients = recpts;
}
void opOpAssign(string op : "~")(EmailRecipient r) {
recipients ~= r;
}
void opOpAssign(string op : "~")(string s) {
recipients ~= EmailRecipient(s);
}
int opApply(int delegate(size_t idx, EmailRecipient rcp) dg) {
foreach(idx, item; recipients)
if(auto result = dg(idx, item))
return result;
return 0;
}
int opApply(int delegate(EmailRecipient rcp) dg) {
foreach(item; recipients)
if(auto result = dg(item))
return result;
return 0;
}
size_t length() {
return recipients.length;
}
string toProtocolString(string linesep = "\r\n") {
string ret;
foreach(idx, item; recipients) {
if(idx)
ret ~= ", ";
ret ~= item.toProtocolString(linesep);
}
return ret;
}
EmailRecipient front() { return recipients[0]; }
void popFront() { recipients = recipients[1 .. $]; }
bool empty() { return recipients.length == 0; }
RecipientList save() { return this; }
}
private string unquote(string s) {
if(s.length == 0)
return s;
if(s[0] != '"')
return s;
s = s[1 .. $-1]; // strip the quotes
// FIXME: possible to have \" escapes in there too
return s;
}
private struct CaseInsensitiveString {
string actual;
size_t toHash() const {
string l = actual.toLower;
return typeid(string).getHash(&l);
}
bool opEquals(ref const typeof(this) s) const {
return icmp(s.actual, this.actual) == 0;
}
bool opEquals(string s) const {
return icmp(s, this.actual) == 0;
}
alias actual this;
}
/++
A type that acts similarly to a `string[string]` to hold email headers in a case-insensitive way.
+/
struct HeadersHash {
string[CaseInsensitiveString] hash;
string opIndex(string key) const {
return hash[CaseInsensitiveString(key)];
}
string opIndexAssign(string value, string key) {
return hash[CaseInsensitiveString(key)] = value;
}
inout(string)* opBinaryRight(string op : "in")(string key) inout {
return CaseInsensitiveString(key) in hash;
}
alias hash this;
}
unittest {
HeadersHash h;
h["From"] = "test";
h["from"] = "other";
foreach(k, v; h) {
assert(k == "From");
assert(v == "other");
}
assert("from" in h);
assert("From" in h);
assert(h["from"] == "other");
const(HeadersHash) ch = HeadersHash([CaseInsensitiveString("From") : "test"]);
assert(ch["from"] == "test");
assert("From" in ch);
}
/++
For OUTGOING email
To use:
---
auto message = new EmailMessage();
message.to ~= "[email protected]";
message.from = "[email protected]";
message.subject = "My Subject";
message.setTextBody("hi there");
//message.toString(); // get string to send externally
message.send(); // send via some relay
// may also set replyTo, etc
---
History:
This class got an API overhaul on May 13, 2024. Some undocumented members were removed, and some public members got changed (albeit in a mostly compatible way).
+/
class EmailMessage {
/++
Adds a custom header to the message. The header name should not include a colon and must not duplicate a header set elsewhere in the class; for example, do not use this to set `To`, and instead use the [to] field.
Setting the same header multiple times will overwrite the old value. It will not set duplicate headers and does not retain the specific order of which you added headers.
History:
Prior to May 13, 2024, this assumed the value was previously encoded. This worked most the time but also left open the possibility of incorrectly encoded values, including the possibility of injecting inappropriate headers.
Since May 13, 2024, it now encodes the header content internally. You should NOT pass pre-encoded values to this function anymore.
It also would previously allow you to set repeated headers like `Subject` or `To`. These now throw exceptions.
It previously also allowed duplicate headers. Adding the same thing twice will now silently overwrite the old value instead.
+/
void setHeader(string name, string value, string file = __FILE__, size_t line = __LINE__) {
import arsd.core;
if(name.length == 0)
throw new InvalidArgumentsException("name", "name cannot be an empty string", LimitedVariant(name), "setHeader", file, line);
if(name.indexOf(":") != -1)
throw new InvalidArgumentsException("name", "do not put a colon in the header name", LimitedVariant(name), "setHeader", file, line);
if(!headerSettableThroughAA(name))
throw new InvalidArgumentsException("name", "use named methods/properties for this header instead of setHeader", LimitedVariant(name), "setHeader", file, line);
headers_[name] = value;
}
protected bool headerSettableThroughAA(string name) {
switch(name.toLower) {
case "to", "cc", "bcc":
case "from", "reply-to", "in-reply-to":
case "subject":
case "content-type", "content-transfer-encoding", "mime-version":
case "received", "return-path": // set by the MTA
return false;
default:
return true;
}
}
/++
Recipients of the message. You can use operator `~=` to add people to this list, or you can also use [addRecipient] to achieve the same result.
---
message.to ~= EmailRecipient("Adam D. Ruppe", "[email protected]");
message.cc ~= EmailRecipient("John Doe", "[email protected]");
// or, same result as the above two lines:
message.addRecipient("Adam D. Ruppe", "[email protected]");
message.addRecipient("John Doe", "[email protected]", ToType.cc);
// or, the old style code that still works, but is not recommended, since
// it is harder to encode properly for anything except pure ascii names:
message.to ~= `"Adam D. Ruppe" <[email protected]>`
---
History:
On May 13, 2024, the types of these changed. Before, they were `public string[]`; plain string arrays. This put the burden of proper encoding on the user, increasing the probability of bugs. Now, they are [RecipientList]s - internally, an array of `EmailRecipient` objects, but with a wrapper to provide compatibility with the old string-based api.
+/
RecipientList to;
/// ditto
RecipientList cc;
/// ditto
RecipientList bcc;
/++
Represents the `From:` and `Reply-To:` header values in the email.
Note that the `from` member is the "From:" header, which is not necessarily the same as the "envelope from". The "envelope from" is set by the email server usually based on your login credentials. The email server may or may not require these to match.
History:
On May 13, 2024, the types of these changed from plain `string` to [EmailRecipient], to try to get the encoding easier to use correctly. `EmailRecipient` offers overloads for string parameters for compatibility, so your code should not need changing, however if you use non-ascii characters in your names, you should retest to ensure it still works correctly.
+/
EmailRecipient from;
/// ditto
EmailRecipient replyTo;
/// The `Subject:` header value in the email.
string subject;
/// The `In-Reply-to:` header value. This should be set to the same value as the `Message-ID` header from the message you're replying to.
string inReplyTo;
private string textBody_;
private string htmlBody_;
private HeadersHash headers_;
/++
Gets and sets the current text body.
History:
Prior to May 13, 2024, this was a simple `public string` member, but still had a [setTextBody] method too. It now is a public property that works through that method.
+/
string textBody() {
return textBody_;
}
/// ditto
void textBody(string text) {
setTextBody(text);
}
/++
Gets the current html body, if any.
There is no setter for this property, use [setHtmlBody] instead.
History:
Prior to May 13, 2024, this was a simple `public string` member. This let you easily get the `EmailMessage` object into an inconsistent state.
+/
string htmlBody() {
return htmlBody_;
}
/++
If you use the send method with an SMTP server, you don't want to change this.
While RFC 2045 mandates CRLF as a lineseperator, there are some edge-cases where this won't work.
When passing the E-Mail string to a unix program which handles communication with the SMTP server, some (i.e. qmail)
expect the system lineseperator (LF) instead.
Notably, the google mail REST API will choke on CRLF lineseps and produce strange emails (as of 2024).
Do not change this after calling other methods, since it might break presaved values.
+/
string linesep = "\r\n";
/++
History:
Added May 13, 2024
+/
this(string linesep = "\r\n") {
this.linesep = linesep;
}
private bool isMime = false;
private bool isHtml = false;
///
void addRecipient(string name, string email, ToType how = ToType.to) {
addRecipient(`"`~name~`" <`~email~`>`, how);
}
///
void addRecipient(string who, ToType how = ToType.to) {
final switch(how) {
case ToType.to:
to ~= who;
break;
case ToType.cc:
cc ~= who;
break;
case ToType.bcc:
bcc ~= who;
break;
}
}
/++
Sets the plain text body of the email. You can also separately call [setHtmlBody] to set a HTML body.
+/
void setTextBody(string text) {
textBody_ = text.strip;
}
/++
Sets the HTML body to the mail, which can support rich text, inline images (see [addInlineImage]), etc.
Automatically sets a text fallback if you haven't already, unless you pass `false` as the `addFallback` template value. Adding the fallback requires [arsd.htmltotext].
History:
The `addFallback` parameter was added on May 13, 2024.
+/
void setHtmlBody(bool addFallback = true)(string html) {
isMime = true;
isHtml = true;
htmlBody_ = html;
static if(addFallback) {
import arsd.htmltotext;
if(textBody_ is null)
textBody_ = htmlToText(html);
}
}
const(MimeAttachment)[] attachments;
/++
The filename is what is shown to the user, not the file on your sending computer. It should NOT have a path in it.
---
message.addAttachment("text/plain", "something.txt", std.file.read("/path/to/local/something.txt"));
---
+/
void addAttachment(string mimeType, string filename, const void[] content, string id = null) {
isMime = true;
attachments ~= MimeAttachment(mimeType, filename, cast(const(ubyte)[]) content, id);
}
/// in the html, use img src="cid:ID_GIVEN_HERE"
void addInlineImage(string id, string mimeType, string filename, const void[] content) {
assert(isHtml);
isMime = true;
inlineImages ~= MimeAttachment(mimeType, filename, cast(const(ubyte)[]) content, id);
}
const(MimeAttachment)[] inlineImages;
/* we should build out the mime thingy
related
mixed
alternate
*/
/// Returns the MIME formatted email string, including encoded attachments
override string toString() {
assert(!isHtml || (isHtml && isMime));
string[] headers;
foreach(k, v; this.headers_) {
if(headerSettableThroughAA(k))
headers ~= k ~ ": " ~ encodeEmailHeaderContentForTransmit(v, this.linesep);
}
if(to.length)
headers ~= "To: " ~ to.toProtocolString(this.linesep);
if(cc.length)
headers ~= "Cc: " ~ cc.toProtocolString(this.linesep);
if(from.length)
headers ~= "From: " ~ from.toProtocolString(this.linesep);
//assert(0, headers[$-1]);
if(subject !is null)
headers ~= "Subject: " ~ encodeEmailHeaderContentForTransmit(subject, this.linesep);
if(replyTo !is null)
headers ~= "Reply-To: " ~ replyTo.toProtocolString(this.linesep);
if(inReplyTo !is null)
headers ~= "In-Reply-To: " ~ encodeEmailHeaderContentForTransmit(inReplyTo, this.linesep);
if(isMime)
headers ~= "MIME-Version: 1.0";
/+
if(inlineImages.length) {
headers ~= "Content-Type: multipart/related; boundary=" ~ boundary;
// so we put the alternative inside asthe first attachment with as seconary boundary
// then we do the images
} else
if(attachments.length)
headers ~= "Content-Type: multipart/mixed; boundary=" ~ boundary;
else if(isHtml)
headers ~= "Content-Type: multipart/alternative; boundary=" ~ boundary;
else
headers ~= "Content-Type: text/plain; charset=UTF-8";
+/
string msgContent;
if(isMime) {
MimeContainer top;
{
MimeContainer mimeMessage;
enum NO_TRANSFER_ENCODING = "Content-Transfer-Encoding: 8bit";
if(isHtml) {
auto alternative = new MimeContainer("multipart/alternative");
alternative.stuff ~= new MimeContainer("text/plain; charset=UTF-8", textBody_).with_header(NO_TRANSFER_ENCODING);
alternative.stuff ~= new MimeContainer("text/html; charset=UTF-8", htmlBody_).with_header(NO_TRANSFER_ENCODING);
mimeMessage = alternative;
} else {
mimeMessage = new MimeContainer("text/plain; charset=UTF-8", textBody_).with_header(NO_TRANSFER_ENCODING);
}
top = mimeMessage;
}
{
MimeContainer mimeRelated;
if(inlineImages.length) {
mimeRelated = new MimeContainer("multipart/related");
mimeRelated.stuff ~= top;
top = mimeRelated;
foreach(attachment; inlineImages) {
auto mimeAttachment = new MimeContainer(attachment.type ~ "; name=\""~attachment.filename~"\"");
mimeAttachment.headers ~= "Content-Transfer-Encoding: base64";
mimeAttachment.headers ~= "Content-ID: <" ~ attachment.id ~ ">";
mimeAttachment.content = encodeBase64Mime(cast(const(ubyte)[]) attachment.content, this.linesep);
mimeRelated.stuff ~= mimeAttachment;
}
}
}
{
MimeContainer mimeMixed;
if(attachments.length) {
mimeMixed = new MimeContainer("multipart/mixed");
mimeMixed.stuff ~= top;
top = mimeMixed;
foreach(attachment; attachments) {
auto mimeAttachment = new MimeContainer(attachment.type);
mimeAttachment.headers ~= "Content-Disposition: attachment; filename=\""~encodeEmailHeaderContentForTransmit(attachment.filename, this.linesep)~"\"";
mimeAttachment.headers ~= "Content-Transfer-Encoding: base64";
if(attachment.id.length)
mimeAttachment.headers ~= "Content-ID: <" ~ attachment.id ~ ">";
mimeAttachment.content = encodeBase64Mime(cast(const(ubyte)[]) attachment.content, this.linesep);
mimeMixed.stuff ~= mimeAttachment;
}
}
}
headers ~= top.contentType;
msgContent = top.toMimeString(true, this.linesep);
} else {
headers ~= "Content-Type: text/plain; charset=UTF-8";
msgContent = textBody_;
}
string msg;
msg.reserve(htmlBody_.length + textBody_.length + 1024);
foreach(header; headers)
msg ~= header ~ this.linesep;
if(msg.length) // has headers
msg ~= this.linesep;
msg ~= msgContent;
return msg;
}
/// Sends via a given SMTP relay
void send(RelayInfo mailServer = RelayInfo("smtp://localhost")) {
auto smtp = SMTP(mailServer.server);
smtp.verifyHost = false;
smtp.verifyPeer = false;
//smtp.verbose = true;
{
// std.net.curl doesn't work well with STARTTLS if you don't
// put smtps://... and if you do, it errors if you can't start
// with a TLS connection from the beginning.
// This change allows ssl if it can.
import std.net.curl;
import etc.c.curl;
smtp.handle.set(CurlOption.use_ssl, CurlUseSSL.tryssl);
}
if(mailServer.username.length)
smtp.setAuthentication(mailServer.username, mailServer.password);
const(char)[][] allRecipients;
void processPerson(string person) {
auto idx = person.indexOf("<");
if(idx == -1)
allRecipients ~= person;
else {
person = person[idx + 1 .. $];
idx = person.indexOf(">");
if(idx != -1)
person = person[0 .. idx];
allRecipients ~= person;
}
}
foreach(person; to) processPerson(person);
foreach(person; cc) processPerson(person);
foreach(person; bcc) processPerson(person);
smtp.mailTo(allRecipients);
auto mailFrom = from;
auto idx = mailFrom.indexOf("<");
if(idx != -1)
mailFrom = mailFrom[idx + 1 .. $];
idx = mailFrom.indexOf(">");
if(idx != -1)
mailFrom = mailFrom[0 .. idx];
smtp.mailFrom = mailFrom;
smtp.message = this.toString();
smtp.perform();
}
}
///
void email(string to, string subject, string message, string from, RelayInfo mailServer = RelayInfo("smtp://localhost")) {
auto msg = new EmailMessage();
msg.from = from;
msg.to = [to];
msg.subject = subject;
msg.textBody_ = message;
msg.send(mailServer);
}
// private:
import std.conv;
/// for reading
class MimePart {
string[] headers;
immutable(ubyte)[] content;
immutable(ubyte)[] encodedContent; // usually valid only for GPG, and will be cleared by creator; canonical form
string textContent;
MimePart[] stuff;
string name;
string charset;
string type;
string transferEncoding;
string disposition;
string id;
string filename;
// gpg signatures
string gpgalg;
string gpgproto;
MimeAttachment toMimeAttachment() {
if(type == "multipart/mixed" && stuff.length == 1)
return stuff[0].toMimeAttachment;
MimeAttachment att;
att.type = type;
if(att.type == "application/octet-stream" && filename.length == 0 && name.length > 0 ) {
att.filename = name;
} else {
att.filename = filename;
}
att.id = id;
att.content = content;
return att;
}
this(immutable(ubyte)[][] lines, string contentType = null) {
string boundary;
void parseContentType(string content) {
//{ import std.stdio; writeln("c=[", content, "]"); }
foreach(k, v; breakUpHeaderParts(content)) {
//{ import std.stdio; writeln(" k=[", k, "]; v=[", v, "]"); }
switch(k) {
case "root":
type = v;
break;
case "name":
name = v;
break;
case "charset":
charset = v;
break;
case "boundary":
boundary = v;
break;
default:
case "micalg":
gpgalg = v;
break;
case "protocol":
gpgproto = v;
break;
}
}
}
if(contentType is null) {
// read headers immediately...
auto copyOfLines = lines;
immutable(ubyte)[] currentHeader;
void commitHeader() {
if(currentHeader.length == 0)
return;
string h = decodeEncodedWord(cast(string) currentHeader);
headers ~= h;
currentHeader = null;
auto idx = h.indexOf(":");
if(idx != -1) {
auto name = h[0 .. idx].strip.toLower;
auto content = h[idx + 1 .. $].strip;
string[4] filenames_found;
switch(name) {
case "content-type":
parseContentType(content);
break;
case "content-transfer-encoding":
transferEncoding = content.toLower;
break;
case "content-disposition":
foreach(k, v; breakUpHeaderParts(content)) {
switch(k) {
case "root":
disposition = v;
break;
case "filename":
filename = v;
break;
// FIXME: https://datatracker.ietf.org/doc/html/rfc2184#section-3 is what it is SUPPOSED to do
case "filename*0":
filenames_found[0] = v;
break;
case "filename*1":
filenames_found[1] = v;
break;
case "filename*2":
filenames_found[2] = v;
break;
case "filename*3":
filenames_found[3] = v;
break;
default:
}
}
break;
case "content-id":
id = content;
break;
default:
}
if (filenames_found[0] != "") {
foreach (string v; filenames_found) {
this.filename ~= v;
}
}
}
}
foreach(line; copyOfLines) {
lines = lines[1 .. $];
if(line.length == 0)
break;
if(line[0] == ' ' || line[0] == '\t')
currentHeader ~= (cast(string) line).stripLeft();
else {
if(currentHeader.length) {
commitHeader();
}
currentHeader = line;
}
}
commitHeader();
} else {
parseContentType(contentType);
}
// if it is multipart, find the start boundary. we'll break it up and fill in stuff
// otherwise, all the data that follows is just content
if(boundary.length) {
immutable(ubyte)[][] partLines;
bool inPart;
foreach(line; lines) {
if(line.startsWith("--" ~ boundary)) {
if(inPart)
stuff ~= new MimePart(partLines);
inPart = true;
partLines = null;
if(line == "--" ~ boundary ~ "--")
break; // all done
}
if(inPart) {
partLines ~= line;
} else {
content ~= line ~ '\n';
}
}
} else {
foreach(line; lines) {
content ~= line;
if(transferEncoding != "base64")
content ~= '\n';
}
}
// store encoded content for GPG (should be cleared by caller if necessary)
encodedContent = content;
// decode the content..
switch(transferEncoding) {
case "base64":
content = Base64.decode(cast(string) content);
break;
case "quoted-printable":
content = decodeQuotedPrintable(cast(string) content);
break;
default:
// no change needed (I hope)
}
if(type.indexOf("text/") == 0) {
if(charset.length == 0)
charset = "latin1";
textContent = convertToUtf8Lossy(content, charset);
}
}
}
string[string] breakUpHeaderParts(string headerContent) {
string[string] ret;
string currentName = "root";
string currentContent;
bool inQuote = false;
bool gettingName = false;
bool ignoringSpaces = false;
foreach(char c; headerContent) {
if(ignoringSpaces) {
if(c == ' ')
continue;
else
ignoringSpaces = false;
}
if(gettingName) {
if(c == '=') {
gettingName = false;
continue;
}
currentName ~= c;
}
if(c == '"') {
inQuote = !inQuote;
continue;
}
if(!inQuote && c == ';') {
ret[currentName] = currentContent;
ignoringSpaces = true;
currentName = null;
currentContent = null;
gettingName = true;
continue;
}
if(!gettingName)
currentContent ~= c;
}
if(currentName.length)
ret[currentName] = currentContent;
return ret;
}
// for writing
class MimeContainer {
private static int sequence;
immutable string _contentType;
immutable string boundary;
string[] headers; // NOT including content-type
string content;
MimeContainer[] stuff;
this(string contentType, string content = null) {
this._contentType = contentType;
this.content = content;
sequence++;
if(_contentType.indexOf("multipart/") == 0)
boundary = "0016e64be86203dd36047610926a" ~ to!string(sequence);
}
@property string contentType() {
string ct = "Content-Type: "~_contentType;
if(boundary.length)
ct ~= "; boundary=" ~ boundary;
return ct;
}
string toMimeString(bool isRoot = false, string linesep="\r\n") {
string ret;
if(!isRoot) {
ret ~= contentType;
foreach(header; headers) {
ret ~= linesep;
ret ~= encodeEmailHeaderForTransmit(header, linesep);
}
ret ~= linesep ~ linesep;
}
ret ~= content;
foreach(idx, thing; stuff) {
assert(boundary.length);
ret ~= linesep ~ "--" ~ boundary ~ linesep;
ret ~= thing.toMimeString(false, linesep);
}
if(boundary.length)
ret ~= linesep ~ "--" ~ boundary ~ "--";
return ret;
}
}
import std.algorithm : startsWith;
/++
Represents a single email from an incoming or saved source consisting of the raw data. Such saved sources include mbox files (which are several concatenated together, see [MboxMessages] for a full reader of these files), .eml files, and Maildir entries.
+/
class IncomingEmailMessage : EmailMessage {
/++
Various constructors for parsing an email message.