forked from andyedinborough/aenetmail
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMailMessage.cs
More file actions
232 lines (203 loc) · 8.46 KB
/
MailMessage.cs
File metadata and controls
232 lines (203 loc) · 8.46 KB
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
namespace AE.Net.Mail {
public enum MailPriority {
Normal = 3,
High = 5,
Low = 1
}
[System.Flags]
public enum Flags {
None = 0,
Seen = 1,
Answered = 2,
Flagged = 4,
Deleted = 8,
Draft = 16
}
public class MailMessage : ObjectWHeaders {
public static implicit operator System.Net.Mail.MailMessage(MailMessage msg) {
var ret = new System.Net.Mail.MailMessage();
ret.Subject = msg.Subject;
ret.Sender = msg.Sender;
foreach (var a in msg.Bcc)
ret.Bcc.Add(a);
ret.Body = msg.Body;
ret.IsBodyHtml = msg.ContentType.Contains("html");
ret.From = msg.From;
ret.Priority = (System.Net.Mail.MailPriority)msg.Importance;
foreach (var a in msg.ReplyTo)
ret.ReplyToList.Add(a);
foreach (var a in msg.To)
ret.To.Add(a);
foreach (var a in msg.Attachments)
ret.Attachments.Add(new System.Net.Mail.Attachment(new System.IO.MemoryStream(a.GetData()), a.Filename, a.ContentType));
foreach (var a in msg.AlternateViews)
ret.AlternateViews.Add(new System.Net.Mail.AlternateView(new System.IO.MemoryStream(a.GetData()), a.ContentType));
return ret;
}
private bool _HeadersOnly; // set to true if only headers have been fetched.
public MailMessage() {
RawFlags = new string[0];
To = new List<MailAddress>();
Cc = new List<MailAddress>();
Bcc = new List<MailAddress>();
ReplyTo = new List<MailAddress>();
Attachments = new List<Attachment>();
AlternateViews = new List<Attachment>();
}
public DateTime Date { get; set; }
public string[] RawFlags { get; set; }
public Flags Flags { get; set; }
public int Size { get; internal set; }
public string Subject { get; set; }
public ICollection<MailAddress> To { get; private set; }
public ICollection<MailAddress> Cc { get; private set; }
public ICollection<MailAddress> Bcc { get; private set; }
public ICollection<MailAddress> ReplyTo { get; private set; }
public ICollection<Attachment> Attachments { get; set; }
public ICollection<Attachment> AlternateViews { get; set; }
public MailAddress From { get; set; }
public MailAddress Sender { get; set; }
public string MessageID { get; set; }
public string Uid { get; internal set; }
public MailPriority Importance { get; set; }
public void Load(string message, bool headersOnly = false) {
using (var mem = new MemoryStream(_DefaultEncoding.GetBytes(message))) {
Load(mem, headersOnly, 0);
}
}
public void Load(Stream reader, bool headersOnly = false, int maxLength = 0) {
_HeadersOnly = headersOnly;
Headers = null;
Body = null;
if (headersOnly) {
RawHeaders = reader.ReadToEnd(maxLength, _DefaultEncoding);
} else {
var headers = new StringBuilder();
string line;
while ((line = reader.ReadLine(ref maxLength, _DefaultEncoding)) != null) {
if (line.Trim().Length == 0)
if (headers.Length == 0)
continue;
else
break;
headers.AppendLine(line);
}
RawHeaders = headers.ToString();
string boundary = Headers.GetBoundary();
if (!string.IsNullOrEmpty(boundary)) {
//else this is a multipart Mime Message
//using (var subreader = new StringReader(line + Environment.NewLine + reader.ReadToEnd()))
ParseMime(reader, boundary, maxLength);
} else {
SetBody(reader.ReadToEnd(maxLength, Encoding).Trim());
}
}
if (string.IsNullOrWhiteSpace(Body) && AlternateViews.Count > 0) {
var att = AlternateViews.FirstOrDefault(x => x.ContentType.Is("text/plain"));
if (att == null) {
att = AlternateViews.FirstOrDefault(x => x.ContentType.Contains("html"));
}
if (att != null) {
Body = att.Body;
ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
ContentType = att.Headers["Content-Type"].RawValue;
}
}
Date = Headers.GetDate();
To = Headers.GetAddresses("To").ToList();
Cc = Headers.GetAddresses("Cc").ToList();
Bcc = Headers.GetAddresses("Bcc").ToList();
Sender = Headers.GetAddresses("Sender").FirstOrDefault();
ReplyTo = Headers.GetAddresses("Reply-To").ToList();
From = Headers.GetAddresses("From").FirstOrDefault();
MessageID = Headers["Message-ID"].RawValue;
Importance = Headers.GetEnum<MailPriority>("Importance");
Subject = Headers["Subject"].RawValue;
}
private void ParseMime(string body, string boundary) {
using (var mem = new MemoryStream(Encoding.GetBytes(body))) {
ParseMime(mem, boundary, 0);
}
}
private void ParseMime(Stream reader, string boundary, int maxLength) {
string data,
bounderInner = "--" + boundary,
bounderOuter = bounderInner + "--";
do {
data = reader.ReadLine(ref maxLength, Encoding);
} while (data != null && !data.StartsWith(bounderInner));
while (data != null && !data.StartsWith(bounderOuter)) {
data = reader.ReadLine(ref maxLength, Encoding);
var a = new Attachment { Encoding = Encoding };
var part = new StringBuilder();
// read part header
while (!data.StartsWith(bounderInner) && data != string.Empty) {
part.AppendLine(data);
data = reader.ReadLine(ref maxLength, Encoding);
}
a.RawHeaders = part.ToString();
// header body
data = reader.ReadLine(ref maxLength, Encoding);
var body = new StringBuilder();
while (data != null && !data.StartsWith(bounderInner)) {
body.AppendLine(data);
data = reader.ReadLine(ref maxLength, Encoding);
}
// check for nested part
string nestedboundary = a.Headers.GetBoundary();
if (!string.IsNullOrEmpty(nestedboundary)) {
ParseMime(body.ToString(), nestedboundary);
} else { // nested
a.SetBody(body.ToString());
(a.IsAttachment ? Attachments : AlternateViews).Add(a);
}
}
data = reader.ReadToEnd(maxLength, Encoding);
}
private static Dictionary<string, int> _FlagCache = System.Enum.GetValues(typeof(Flags)).Cast<Flags>().ToDictionary(x => x.ToString(), x => (int)x, StringComparer.OrdinalIgnoreCase);
internal void SetFlags(string flags) {
RawFlags = flags.Split(' ').Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
Flags = (Flags)RawFlags.Select(x => {
int flag = 0;
if (_FlagCache.TryGetValue(x.TrimStart('\\'), out flag))
return flag;
else
return 0;
}).Sum();
}
public void Save(System.IO.Stream stream, Encoding encoding = null) {
using (var str = new System.IO.StreamWriter(stream, encoding ?? System.Text.Encoding.Default))
Save(str);
}
private static readonly string[] SpecialHeaders = "Date,To,Cc,Reply-To,Bcc,Sender,From,Message-ID,Importance,Subject".Split(',');
public void Save(System.IO.TextWriter txt) {
txt.WriteLine("Date: {0}", Date.GetRFC2060Date());
txt.WriteLine("To: ", string.Join("; ", To.Select(x => x.ToString())));
txt.WriteLine("Cc: ", string.Join("; ", Cc.Select(x => x.ToString())));
txt.WriteLine("Reply-To: ", string.Join("; ", ReplyTo.Select(x => x.ToString())));
txt.WriteLine("Bcc: ", string.Join("; ", Bcc.Select(x => x.ToString())));
if (Sender != null)
txt.WriteLine("Sender: ", Sender);
if (From != null)
txt.WriteLine("From: ", Sender);
if (!string.IsNullOrEmpty(MessageID))
txt.WriteLine("Message-ID: ", MessageID);
var otherHeaders = Headers.Where(x => !SpecialHeaders.Contains(x.Key, StringComparer.InvariantCultureIgnoreCase));
foreach (var header in otherHeaders) {
txt.WriteLine("{0}: {1}", header.Key, header.Value);
}
if (Importance != MailPriority.Normal)
txt.WriteLine("Importance: {0}", (int)Importance);
txt.WriteLine("Subject: {0}", Subject);
txt.WriteLine();
//todo: attachments
txt.Write(Body);
}
}
}