.net c# 使用 MailKit库接收139邮箱邮件
开发工具 vs2022,新建-控制台应用。项目完整代码下载:
要安装MailKit库
using MailKit;
using MailKit.Net.Imap;
using MimeKit;
using System.Text;
namespace MailKit_mail
{
internal class Program
{
static void Main(string[] args)
{
//需要使用 MailKit 库 Install-Package MailKit
//注册字符集,缺失字符集,一些中文编码数据为乱码 --千万别删,不然就是乱码了 //参考:https://blog.csdn.net/qq_44384774/article/details/139686615
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
// IMAP服务器的信息
string host = "imap.139.com";
int port = 993;
bool useSsl = true;
string username = "138********@139.com"; //账号
string password = "***************"; //密码
using (var imapClient = new ImapClient())
{
// 连接到IMAP服务器
imapClient.Connect(host, port, useSsl);
// 登录到邮箱
imapClient.Authenticate(username, password);
// 选择INBOX文件夹
imapClient.Inbox.Open(FolderAccess.ReadOnly);
// 获取INBOX中所有的邮件
var count = imapClient.Inbox.Count;
Console.WriteLine("邮件数量:{0}", count);
// 获取邮件
for (int i = 0; i < 20; i++)
{
MimeMessage message = imapClient.Inbox.GetMessage(i);
//Console.WriteLine("{0}主题:{1}", i.ToString(), message.Subject);
Console.WriteLine($"\r\n标题:{message.Subject} \r\n内容:{message.TextBody}\r\n");
// 处理邮件附件
foreach (var attachment in message.Attachments)
{
if (attachment.IsAttachment)
if (attachment is MimePart)
{
var part = (MimePart)attachment;
var fileName = part.FileName;
//var filePath = "D:\\tmp\\" + Guid.NewGuid().ToString() + fileName;
var filePath = "D:\\tmp\\" + fileName;
//File.Create(filePath)
using (var stream = File.Create(filePath))
{
if (attachment is MessagePart rfc822)
{
rfc822.Message.WriteTo(stream);
}
else
{
part.Content.DecodeTo(stream);
}
}
// 保存附件到本地文件
var mailFileInfo = new FileInfo(filePath);
}
}//附件end
}
imapClient.Disconnect(true);
}
}
}
}
运行截图:
原文地址:https://blog.csdn.net/mangge/article/details/143501345
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!