c#通过Mailkit包封闭获取邮件类

154 154
MailKit
Jordan
Jordan 2024-10-16 23:44:13

概述

通过MailKit来获取指定邮箱所有的邮件主题

代码

public class AdfMail
{
    /// <summary>
    /// 主机
    /// </summary>
    public String Host { get; set; }

    /// <summary>
    /// 端口号
    /// </summary>
    public int Port { get; set; } = 0;

    /// <summary>
    /// 是否启用ssl
    /// </summary>
    public Boolean UseSsl { get; set; }

    /// <summary>
    /// 当前邮箱
    /// </summary>
    public String UserName { get; set; }

    /// <summary>
    /// 密码或者授权码,qq邮箱通过授权码来保护邮箱密码
    /// </summary>
    public String UserPassword { get; set; }
    public AdfMail()
    {

    }

    /// <summary>
    /// 邮件
    /// </summary>
    /// <param name="host"></param>
    /// <param name="port"></param>
    /// <param name="useSsl"></param>
    public AdfMail(String host, int port, bool useSsl=true)
    {
        Host = host;
        Port = port;
        UseSsl = useSsl;
    }

    /// <summary>
    /// 邮件
    /// </summary>
    /// <param name="host"></param>
    /// <param name="port"></param>
    /// <param name="useSsl"></param>
    public AdfMail(String host, string userName, string userPassword, int port=0, bool useSsl = true)
    {
        Host = host;
        Port = port;
        UseSsl = useSsl;
        UserName = userName;
        UserPassword = userPassword;
    }

    /// <summary>
    /// 得到当前邮箱所有的所有邮件的主题
    /// </summary>
    /// <returns></returns>

    public List<String> GetAllSubject()
    {
        List<String> lstInfo = new List<string>();
        using (var client = new ImapClient())
        {

            try
            {
                //连接邮箱
                client.Connect(Host, Port, UseSsl);

                //登录
                client.Authenticate(UserName, UserPassword);

                //打开收件箱

                var inBox = client.Inbox;

                //采用只读的方式打开收件箱,获取收内容
                inBox.Open(FolderAccess.ReadOnly);

                //遍历当前邮箱所有的邮件

                foreach (var uniqueId in inBox.Search(SearchQuery.All))
                {
                    var message = inBox.GetMessage(uniqueId);
                    lstInfo.Add(message.Subject);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        return lstInfo;
    }

}

代码说明

  • 有些邮箱通过授权码来进行客户端登录,比如mail.qq.com
  • 以上示例只展现了获取一个邮箱所有的邮件
回帖
  • 消灭零回复
作者信息
相关文章