Pop3cli

Форк
0
/
Program.cs 
311 строк · 10.4 Кб
1
#region License
2
//------------------------------------------------------------------------------
3
// Copyright (c) Dmitrii Evdokimov
4
// Source https://github.com/diev/
5
// 
6
// Licensed under the Apache License, Version 2.0 (the "License");
7
// you may not use this file except in compliance with the License.
8
// You may obtain a copy of the License at
9
// http://www.apache.org/licenses/LICENSE-2.0
10
// Unless required by applicable law or agreed to in writing, software
11
// distributed under the License is distributed on an "AS IS" BASIS,
12
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
// See the License for the specific language governing permissions and
14
// limitations under the License.
15
//------------------------------------------------------------------------------
16
#endregion
17

18
#define TRACE
19

20
using Lib;
21

22
using Mime;
23

24
using Pop3;
25

26
using System;
27
using System.Collections.Generic;
28
using System.Configuration;
29
using System.IO;
30
using System.Text;
31

32
namespace Pop3cli
33
{
34
    class Program
35
    {
36
        static void Main(string[] args)
37
        {
38
            Console.WriteLine(App.Banner);
39

40
            //AppTrace.Information(App.Title);
41
            AppTrace.Verbose(Environment.CommandLine);
42

43
            //if (args.Length == 0)// || Environment.CommandLine.Contains("?"))
44
            //Usage(null, 2);
45

46

47
            //Console.WriteLine("====================");
48
            //Console.WriteLine();
49

50
            //string src = Path.Combine(AppConfig.Get("Eml"), "3935?.eml");
51

52
            var settings = ConfigurationManager.AppSettings;
53

54
            switch (args.Length)
55
            {
56
                case 0:
57
                    {
58
                        string host = settings["Host"];
59

60
                        if (host.Contains("*"))
61
                        {
62
                            AppTrace.Error("Требуется настроить config!");
63

64
                            Usage();
65
                        }
66

67
                        string src = settings["Src"].ExpandPath();
68
                        string bak = settings["Bak"].ExpandPath();
69
                        string dst = settings["Dst"].ExpandPath();
70

71
                        if (string.IsNullOrEmpty(host))
72
                        {
73
                            AppTrace.Information("Распаковка вложений");
74

75
                            ExtractAttachmentsFromFiles(src, dst);
76
                        }
77
                        else
78
                        {
79
                            AppTrace.Information("Загрузка сообщений");
80

81
                            int port = int.Parse(settings["Port"] ?? "110");
82
                            bool ssl = (settings["Ssl"] ?? "0").Equals("1");
83

84
                            string user = settings["User"];
85
                            string pass = settings["Pass"];
86

87
                            LoadMessages(host, port, ssl, user, pass, src, bak, dst);
88
                        }
89
                        break;
90
                    }
91

92
                case 1:
93
                    {
94
                        string arg = args[0];
95

96
                        if (arg.Equals("-?") || arg.Equals("/?"))
97
                        {
98
                            Usage();
99
                        }
100
                        else
101
                        {
102
                            AppTrace.Information($"Распаковка вложений из {arg}");
103

104
                            string dst = settings["Dst"].ExpandPath();
105
                            ExtractAttachmentsFromFiles(arg, dst);
106
                        }
107
                        break;
108
                    }
109

110
                case 2:
111
                    {
112
                        string arg1 = args[0];
113
                        string arg2 = args[1];
114

115
                        AppTrace.Information($"Распаковка вложений из {arg1} в {arg2}");
116

117
                        ExtractAttachmentsFromFiles(arg1, arg2);
118
                        break;
119
                    }
120

121
                default:
122
                    {
123
                        Usage();
124
                        break;
125
                    }
126
            }
127
#if DEBUG
128
            Console.WriteLine();
129
            Console.WriteLine("======== Press Enter to end program");
130
            Console.ReadLine();
131
#endif
132
            //AppExit.Information("Сделано.");
133
            AppExit.Exit();
134
        }
135

136
        static void Usage()
137
        {
138
            const string usage = "Параметры запуска:\n" +
139
                "0: Читать файл конфигурации и, если указан Host, загрузить файлы с этого POP3 сервера,\n" +
140
                "   если нет - просто распаковать все вложения из файлов по маске Src в папку Dst.\n\n" +
141
                "1: Если -? или /h - показать эту помощь, иначе - по указанной маске вместо Src в конфиге.\n\n" +
142
                "2: Использовать указанные параметры вместо Src и Dst в конфиге.";
143

144
            Console.WriteLine(usage);
145
            //AppExit.Information("О программе.");
146

147
            Environment.Exit(1);
148
        }
149

150
        private static void ExtractAttachmentsFromFiles(string src, string dst)
151
        {
152
            if (Directory.Exists(src))
153
            {
154
                string[] files = Directory.GetFiles(src);
155

156
                foreach (string file in files)
157
                {
158
                    Extract(file, dst);
159
                }
160
            }
161

162
            else if (src.Contains("*") || src.Contains("?"))
163
            {
164
                string path = Path.GetDirectoryName(src);
165

166
                if (!Directory.Exists(path))
167
                {
168
                    AppExit.Error($"{path} not exists!", 2);
169
                }
170

171
                string[] files = Directory.GetFiles(path, Path.GetFileName(src));
172

173
                foreach (string file in files)
174
                {
175
                    Extract(file, dst);
176
                }
177
            }
178
            else if (File.Exists(src))
179
            {
180
                Extract(src, dst);
181
            }
182
            else
183
            {
184
                AppExit.Error($"{src} not found!");
185
            }
186
        }
187

188
        private static void LoadMessages(string host, int port, bool ssl, string user, string pass, string src, string bak, string dst)
189
        {
190
            try
191
            {
192
                //prepare pop client
193
                var client = new Pop3MailClient(host, port, ssl, user, pass)
194
                {
195
                    AutoReconnect = true
196
                };
197

198
                //remove the following line if no tracing is needed
199
                //client.Trace += new Pop3.TraceHandler(Console.WriteLine);
200
                client.Trace += new TraceHandler(AppTrace.Verbose);
201
                client.ReadTimeout = 180000; //give server 180 seconds to answer
202

203
                //establish connection
204
                client.Connect();
205

206
                //get mailbox statistics
207
                client.GetMailboxStats(out int NumberOfMails, out int MailboxSize);
208

209
                //get a list of unique mail ids
210
                client.GetUniqueEmailIdList(out List<Pop3.EmailUid> EmailUids);
211

212
                //get email
213
                for (int i = 0; i < EmailUids.Count; i++)
214
                {
215
                    string path = Path.Combine(src, EmailUids[i].Uid + ".eml");
216

217
                    if (!File.Exists(path))
218
                    {
219
                        int id = EmailUids[i].EmailId;
220

221
                        if (client.GetRawEmail(id, out string text))
222
                        {
223
                            File.WriteAllText(path, text);
224
                            Extract(path, dst);
225
                        }
226
                    }
227
                }
228

229
                //cleanup server deleted email
230
                if (!Directory.Exists(bak))
231
                {
232
                    Directory.CreateDirectory(bak);
233
                }
234

235
                string[] files = Directory.GetFiles(src, "*.eml");
236

237
                foreach (string file in files)
238
                {
239
                    string filename = Path.GetFileNameWithoutExtension(file);
240
                    bool found = false;
241

242
                    foreach (var e in EmailUids)
243
                    {
244
                        if (e.Uid.Equals(filename))
245
                        {
246
                            found = true;
247
                            break;
248
                        }
249
                    }
250

251
                    if (!found)
252
                    {
253
                        AppTrace.Verbose("{0} bak", filename);
254
                        File.Move(file, Path.Combine(bak, filename + ".eml"));
255
                    }
256
                }
257

258
                //close connection
259
                client.Disconnect();
260
            }
261
            catch (Exception ex)
262
            {
263
                var sb = new StringBuilder();
264
                sb
265
                    .AppendLine("Run Time Error Occured:")
266
                    .AppendLine(ex.Message)
267
                    .AppendLine(ex.StackTrace);
268

269
                AppTrace.Error(sb);
270
            }
271
        }
272

273
        private static void Extract(string path, string folder)
274
        {
275
            using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
276
            using (var streamReader = new StreamReader(fileStream))
277
            {
278
                MimeParser parser = new MimeParser(streamReader);
279

280
                if (parser.GetEmail(out MimeMessage message))
281
                {
282
#if DEBUG
283
                    Console.WriteLine(message.MailStructure());
284
#endif
285
                    var sb = new StringBuilder();
286
                    sb
287
                        .AppendLine($"[{Path.GetFileName(path)}] {message.DeliveryDate:dd.MM HH:mm} <{message.From.Address}> {message.From.DisplayName}")
288
                        .AppendLine($"  {message.Subject}");
289

290
                    if (!Directory.Exists(folder))
291
                    {
292
                        Directory.CreateDirectory(folder);
293
                    }
294

295
                    foreach (var attachment in message.Attachments)
296
                    {
297
                        string name = attachment.Name;
298
                        sb.AppendLine($"  - {name}");
299

300
                        using (var file = File.OpenWrite(Path.Combine(folder, name)))
301
                        {
302
                            attachment.ContentStream.CopyTo(file);
303
                        }
304
                    }
305

306
                    AppTrace.Information(sb);
307
                }
308
            }
309
        }
310
    }
311
}
312

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.