安装库MailKit
发送邮件
/// <summary> /// 发送邮件 /// </summary> /// <param name="subject">邮件主题</param> /// <param name="body">邮件内容</param> public void SendEmail(string subject, string body) { var message = new MimeMessage(); message.From.Add(new MailboxAddress("邮箱的名称", "[email protected]")); message.To.Add(new MailboxAddress("邮箱的名称", "接收方@exam.com")); message.Subject = subject; var bodyBuilder = new BodyBuilder { HtmlBody = body }; message.Body = bodyBuilder.ToMessageBody(); using (var smtpClient = new SmtpClient()) { smtpClient.Connect("smtp.qq.com", 465, true); // 服务器地址、端口、加密方式 ssl加密端口465、587 以QQ邮箱为例,具体的服务器地址去对应邮箱官网获取 smtpClient.Authenticate("[email protected]", "授权码"); // 邮箱登录凭证 smtpClient.Send(message); smtpClient.Disconnect(true); } }
注:
关于授权码,需要去发送方邮箱的官网获取授权码,以QQ邮箱为例,登录QQ邮箱进入设置=》账号=》账号安全=》开启服务,跟着指示向下执行,就很可以获取授权码
收取邮件
/// <summary> /// 收取邮件 /// </summary> /// <returns></returns> public async Task ReceiveEmailAsync() { using (var client=new ImapClient()) { await client.ConnectAsync("imap.qq.com", 993,true);//ssl 端口993 以QQ邮箱为例 await client.AuthenticateAsync("[email protected]", "授权码"); var inbox = client.Inbox; await inbox.OpenAsync(MailKit.FolderAccess.ReadOnly); foreach(var uid in await inbox.SearchAsync(SearchQuery.NotSeen))//此处获取未查看的邮件 { var message=await inbox.GetMessageAsync(uid); Console.WriteLine($"Subject:{message.Subject}"); } await client.DisconnectAsync(true); } }
注:根据需求向inbox.SearchAsync()中传入需要查看邮件的分类标签:Core,MailKit,new,var,邮箱,NET,com,message,邮件 From: https://www.cnblogs.com/sugarwxx/p/18410188