forked from andyedinborough/aenetmail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Attachment.cs
71 lines (62 loc) · 2.13 KB
/
Attachment.cs
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
using System;
namespace AE.Net.Mail {
public class Attachment : ObjectWHeaders {
public Attachment() { }
public Attachment(byte[] data, string contentType, string name = null, bool isAttachment = false)
: this(contentType, name, isAttachment) {
SetBody(data);
}
public Attachment(string data, string contentType, string name = null, bool isAttachment = false)
: this(contentType, name, isAttachment) {
SetBody(data);
}
private Attachment(string contentType, string name, bool isAttachment) {
Headers.Add("Content-Type", contentType);
if (!string.IsNullOrEmpty(name)) {
var contentDisposition = new HeaderValue(isAttachment ? "attachment" : "inline");
Headers.Add("Content-Disposition", contentDisposition);
contentDisposition[isAttachment ? "filename" : "name"] = name;
}
}
public virtual string Filename {
get {
return Headers["Content-Disposition"]["filename"].NotEmpty(
Headers["Content-Disposition"]["name"],
Headers["Content-Type"]["filename"],
Headers["Content-Type"]["name"]);
}
}
private string _ContentDisposition;
private string ContentDisposition {
get { return _ContentDisposition ?? (_ContentDisposition = Headers["Content-Disposition"].Value.ToLower()); }
}
public virtual bool OnServer { get; internal set; }
internal bool IsAttachment {
get {
return ContentDisposition == "attachment" || !string.IsNullOrEmpty(Filename);
}
}
public virtual void Save(string filename) {
using (var file = new System.IO.FileStream(filename, System.IO.FileMode.Create))
Save(file);
}
public virtual void Save(System.IO.Stream stream) {
var data = GetData();
stream.Write(data, 0, data.Length);
}
public virtual byte[] GetData() {
byte[] data;
var body = Body;
if (ContentTransferEncoding.Is("base64") && Utilities.IsValidBase64String(ref body)) {
try {
data = Convert.FromBase64String(body);
} catch (Exception) {
data = Encoding.GetBytes(body);
}
} else {
data = Encoding.GetBytes(body);
}
return data;
}
}
}