Przeglądaj źródła

接收邮件标题,正文html,附件,写入本地文件
bug存在(正文html中图片无法显示)

yuqian 8 lat temu
rodzic
commit
59d0d2b358

+ 7 - 3
DemoMailKit/MyMailKit/Config/Mail.json

@@ -1,7 +1,11 @@
1 1
 {
2 2
   "Name": "MyMailSys",
3
-  "Host": "smtp.163.com",
3
+  "SMPTHost": "smtp.163.com",
4 4
   "Address": "yq1989135147@163.com",
5
-  "Password": "yq@198913",
6
-  "Port": 25
5
+  "Password": "yq198913",
6
+  "Port": 25,
7
+  "IMAPAddress": "373168696@qq.com",
8
+  "IMAPPassword": "gkgroldhifwybjgh",
9
+  "IMAPHost": "imap.qq.com",
10
+  "IMAPPort": 993
7 11
 }

+ 23 - 3
DemoMailKit/MyMailKit/Controllers/MailController.cs

@@ -2,10 +2,17 @@
2 2
 using System.Collections.Generic;
3 3
 using System.IO;
4 4
 using System.Linq;
5
+using System.Text;
5 6
 using System.Threading.Tasks;
7
+using MailKit;
8
+using MailKit.Net.Imap;
9
+using MailKit.Search;
10
+using Microsoft.AspNetCore.Hosting;
6 11
 using Microsoft.AspNetCore.Mvc;
7 12
 using Microsoft.Extensions.Options;
13
+using MimeKit;
8 14
 using MyMailKit.Models.Dtos;
15
+using Newtonsoft.Json;
9 16
 using Utility;
10 17
 using Utility.Mail;
11 18
 
@@ -18,13 +25,18 @@ namespace MyMailKit.Controllers
18 25
     public class MailController : Controller
19 26
     {
20 27
         private readonly MailConfig mailConfig;
21
-        public MailController(IOptions<MailConfig> configClassAccesser)
28
+        private readonly IHostingEnvironment _hostingEnvironment;
29
+        public MailController(
30
+            IOptions<MailConfig> configClassAccesser,
31
+            IHostingEnvironment hostingEnvironment
32
+            )
22 33
         {
23 34
             mailConfig = configClassAccesser.Value;
35
+            _hostingEnvironment = hostingEnvironment;
24 36
         }
25 37
 
26 38
         [HttpPost]
27
-        public async Task<string> SendMail(MailDto dto)
39
+        public async Task<string> SendMail(MailInput dto)
28 40
         {
29 41
             List<string> fileNameList = new List<string>();
30 42
             List<Stream> streamList = new List<Stream>();
@@ -45,5 +57,13 @@ namespace MyMailKit.Controllers
45 57
             return "发送失败";
46 58
         }
47 59
 
60
+
61
+        public async Task<string> GetMail()
62
+        {
63
+            var webRootPath = _hostingEnvironment.WebRootPath;
64
+            var contentRootPaht = _hostingEnvironment.ContentRootPath;
65
+            var list = await MailUtil.GetMail(mailConfig, webRootPath);
66
+            return JsonConvert.SerializeObject(list);
67
+        }
48 68
     }
49
-}
69
+}

+ 1 - 1
DemoMailKit/MyMailKit/Models/Dtos/MailDtos.cs

@@ -5,7 +5,7 @@ using System.Threading.Tasks;
5 5
 
6 6
 namespace MyMailKit.Models.Dtos
7 7
 {
8
-    public class MailDto
8
+    public class MailInput
9 9
     {
10 10
         /// <summary>
11 11
         /// 邮件标题

+ 3 - 0
DemoMailKit/MyMailKit/MyMailKit.csproj

@@ -11,6 +11,7 @@
11 11
   <ItemGroup>
12 12
     <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.5" />
13 13
     <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.2" />
14
+    <PackageReference Include="Newtonsoft.Json" Version="11.0.1" />
14 15
   </ItemGroup>
15 16
 
16 17
   <ItemGroup>
@@ -27,4 +28,6 @@
27 28
     </Content>
28 29
   </ItemGroup>
29 30
 
31
+  <ProjectExtensions><VisualStudio><UserProperties appsettings_1json__JSONSchema="" /></VisualStudio></ProjectExtensions>
32
+
30 33
 </Project>

+ 1 - 1
DemoMailKit/MyMailKit/Properties/launchSettings.json

@@ -18,7 +18,7 @@
18 18
     },
19 19
     "MyMailKit": {
20 20
       "commandName": "Project",
21
-      "launchBrowser": true,
21
+      "launchBrowser": false,
22 22
       "launchUrl": "api/values",
23 23
       "environmentVariables": {
24 24
         "ASPNETCORE_ENVIRONMENT": "Development"

+ 10 - 1
DemoMailKit/Utility/Mail/MailConfig.cs

@@ -22,11 +22,20 @@ namespace Utility.Mail
22 22
         /// <summary>
23 23
         /// 发件人邮箱SMTP服务器地址
24 24
         /// </summary>
25
-        public string Host { get; set; }
25
+        public string SMPTHost { get; set; }
26 26
         /// <summary>
27 27
         /// 端口
28 28
         /// </summary>
29 29
         public int Port { get; set; }
30 30
 
31
+        public string IMAPAddress { get; set; }
32
+        public string IMAPPassword { get; set; }
33
+        /// <summary>
34
+        /// 
35
+        /// </summary>
36
+        public string IMAPHost { get; set; }
37
+        public int IMAPPort { get; set; }
38
+
39
+
31 40
     }
32 41
 }

+ 17 - 0
DemoMailKit/Utility/Mail/MailOutput.cs

@@ -0,0 +1,17 @@
1
+using MimeKit;
2
+using System;
3
+using System.Collections.Generic;
4
+using System.Linq;
5
+using System.Threading.Tasks;
6
+
7
+namespace Utility.Mail
8
+{
9
+    public class MailOutput
10
+    {
11
+        public string Id { get; set; }
12
+        public string Subject { get; set; }
13
+        public DateTime Date { get; set; }
14
+        public string Html { get; set; }
15
+
16
+    }
17
+}

+ 109 - 3
DemoMailKit/Utility/Mail/MailUtil.cs

@@ -1,9 +1,13 @@
1
-using MailKit.Net.Smtp;
1
+using MailKit;
2
+using MailKit.Net.Imap;
3
+using MailKit.Net.Smtp;
4
+using MailKit.Search;
2 5
 using MimeKit;
3 6
 using System;
4 7
 using System.Collections.Generic;
5 8
 using System.IO;
6 9
 using System.Linq;
10
+using System.Text;
7 11
 using System.Threading.Tasks;
8 12
 
9 13
 namespace Utility.Mail
@@ -20,7 +24,7 @@ namespace Utility.Mail
20 24
             {
21 25
                 var smtpClient = new SmtpClient();
22 26
                 smtpClient.Timeout = 10 * 1000;   //设置超时时间
23
-                smtpClient.Connect(config.Host, config.Port, MailKit.Security.SecureSocketOptions.None);//连接到远程smtp服务器
27
+                smtpClient.Connect(config.SMPTHost, config.Port, MailKit.Security.SecureSocketOptions.None);//连接到远程smtp服务器
24 28
                 smtpClient.Authenticate(config.Address, config.Password);
25 29
                 await smtpClient.SendAsync(mailMessage);//发送邮件
26 30
                 smtpClient.Disconnect(true);
@@ -90,5 +94,107 @@ namespace Utility.Mail
90 94
             return await SendMail(mailMessage, config);
91 95
 
92 96
         }
97
+
98
+        /// <summary>
99
+        /// 接收邮件
100
+        /// </summary>
101
+        /// <param name="config"></param>
102
+        /// <param name="webRootPath"></param>
103
+        /// <returns></returns>
104
+        public async static Task<List<MailOutput>> GetMail(MailConfig config, string webRootPath)
105
+        {
106
+            List<MailOutput> list = new List<MailOutput>();
107
+            using (var client = new ImapClient())
108
+            {
109
+                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
110
+
111
+                await client.ConnectAsync(config.IMAPHost, config.IMAPPort, true);
112
+
113
+                await client.AuthenticateAsync(config.IMAPAddress, config.IMAPPassword);
114
+
115
+                var inbox = client.Inbox;
116
+                await inbox.OpenAsync(FolderAccess.ReadOnly);
117
+
118
+                var unids = await inbox.SearchAsync(SearchQuery.NotSeen);
119
+
120
+
121
+
122
+                foreach (var summary in await inbox.FetchAsync(unids, MessageSummaryItems.UniqueId | MessageSummaryItems.Envelope | MessageSummaryItems.BodyStructure))
123
+                {
124
+                    var directory = Path.Combine(webRootPath, summary.UniqueId.ToString());
125
+
126
+                    if (!Directory.Exists(directory))
127
+                    {
128
+                        Directory.CreateDirectory(directory);
129
+                    }
130
+
131
+                    //邮件列表
132
+                    list.Add(new MailOutput
133
+                    {
134
+                        Id = summary.UniqueId.ToString(),
135
+                        Date = summary.Date.DateTime,
136
+                        Subject = summary.Envelope.Subject
137
+                    });
138
+
139
+                    //if (summary.TextBody != null)
140
+                    //{
141
+                    //    // this will download *just* the text/plain part
142
+                    //    var text = await inbox.GetBodyPartAsync(summary.UniqueId, summary.TextBody);
143
+                    //    var part = (MimePart)text;
144
+                    //    var fileName = "TextBody.txt";
145
+                    //    var path = Path.Combine(directory, fileName);
146
+                    //    using (var stream = System.IO.File.Create(path))
147
+                    //    {
148
+                    //        await part.Content.DecodeToAsync(stream);
149
+                    //    }
150
+                    //}
151
+
152
+                    if (summary.HtmlBody != null)
153
+                    {
154
+                        // this will download *just* the text/html part
155
+                        var html = await inbox.GetBodyPartAsync(summary.UniqueId, summary.HtmlBody);
156
+                        var part = (MimePart)html;
157
+                        var fileName = "HtmlBody.txt";
158
+                        var path = Path.Combine(directory, fileName);
159
+                        using (var stream = System.IO.File.Create(path))
160
+                        {
161
+                            await part.Content.DecodeToAsync(stream);
162
+                        }
163
+                    }
164
+
165
+
166
+                    if (summary.Body is BodyPartMultipart)
167
+                    {
168
+                        foreach (var attachment in summary.Attachments)
169
+                        {
170
+                            // this will download *just* the attachment
171
+                            var entity = await inbox.GetBodyPartAsync(summary.UniqueId, attachment);
172
+
173
+                            if (entity is MessagePart)
174
+                            {
175
+                                var rfc822 = (MessagePart)entity;
176
+                                var path = Path.Combine(directory, attachment.PartSpecifier + ".eml");
177
+                                rfc822.Message.WriteTo(path);
178
+                            }
179
+                            else
180
+                            {
181
+                                var part = (MimePart)entity;
182
+                                var fileName = part.FileName;
183
+                                var path = Path.Combine(directory, fileName);
184
+                                using (var stream = System.IO.File.Create(path))
185
+                                {
186
+                                    await part.Content.DecodeToAsync(stream);
187
+                                }
188
+                            }
189
+                        }
190
+                    }
191
+                }
192
+
193
+                await client.DisconnectAsync(true);
194
+            }
195
+
196
+            return list;
197
+
198
+        }
93 199
     }
94
-}
200
+}