読者です 読者をやめる 読者になる 読者になる

IT業界のすみっこ暮らし

ふと気がついたときの記録

C#でメール受信・削除(OpenPoP.NET)

開発 C# .NET

参考サイト hpop.sourceforge.net
メール受信・削除呼び出し

using (Pop3Client pop3Client = GetPop3Client())
{
    var pop3 = new Pop3Mail();
    List<MailInfo> receivedMailList = pop3.ReceiveMails(pop3Client);
    pop3.DeleteMessageByMessageId(client, 1); // MessageId
}


Pop3Client生成

public static Pop3Client GetPop3Client()
{
    string host = ConfigurationManager.AppSettings["pop.host"];
    int port = Convert.ToInt32(ConfigurationManager.AppSettings["pop.port"]);
    string username = ConfigurationManager.AppSettings["pop.username"];
    string password = ConfigurationManager.AppSettings["pop.password"];

    var client = new Pop3Client();
    client.Connect(host, port, true);
    client.Authenticate(username, password);

    return client;
}


Web.config or App.config

<appSettings>
  <add key="pop.host" value="host" />
  <add key="pop.port" value="port" />
  <add key="pop.username" value="username" />
  <add key="pop.password" value="password" />
</appSettings>


メール受信・削除用メソッド

using OpenPop.Mime;
using OpenPop.Pop3;
using System;
using System.Collections.Generic;
using System.Configuration;
using Message = OpenPop.Mime.Message;

public class Pop3Mail {

public List<MailInfo> ReceiveMails(Pop3Client client)
{   
    var receivedMailList = new List<MailInfo>();
    int messageCount = client.GetMessageCount();
    string subject = string.Empty;
    string body = string.Empty;

    for (int i = messageCount; i >= 1; i -= 1)
    {
        Message message = client.GetMessage(i);
        MessagePart plainTextPart = message.FindFirstPlainTextVersion();
        subject = message.Headers.Subject;
        body = plainTextPart.GetBodyAsText();

        var mailInfo = new MailInfo();
        mailInfo.CurrentSubject = subject;
        mailInfo.CurrentBody = body;
        mailInfo.CurrentMessageID = message.Headers.MessageId;
        receivedMailList.Add(mailInfo);
    }
    return receivedMailList;
}

public void DeleteMessageByMessageId(Pop3Client client, string messageId)
{
    try
    {
        int messageCount = client.GetMessageCount();

        for (int messageItem = messageCount; messageItem > 0; messageItem--)
        {
            if (client.GetMessageHeaders(messageItem).MessageId == messageId)
            {
                client.DeleteMessage(messageItem);
            }
        }
    }
    catch (Exception e)
    {
        // 「既に削除済み」の場合はエラー処理をしない
        if (e.Message.IndexOf("ERR Message is deleted") == -1)
        {
            throw new Exception("メール削除時に例外が発生しました。");
        }
    }
}
}


メール受信内容クラス

public class MailInfo
{
    public string CurrentMessageID { get; set; }
    public string CurrentSubject { get; set; }
    public string CurrentBody { get; set; }
    public string PreviousMessageID { get; set; }
    public string PreviousSubject { get; set; }
    public string PreviousBody { get; set; }
}