前回、MailBee.NET でメールの送信を行ったので、ついでに受信も行ってみます。

MailBee.NET Objects
http://www.afterlogic.com/products/net-email-components

 

POP3でメールを受信する場合

 
        static void Main(string[] args)
        {
            MailBee.Pop3Mail.Pop3.LicenseKey = "ライセンスキー";
            MailBee.Pop3Mail.Pop3 pop3 = new MailBee.Pop3Mail.Pop3();
            
            pop3.Connect("POP3サーバーアドレス");
            pop3.Login("アカウント", "パスワード");
            
            for (int i = 1, max = pop3.InboxMessageCount; i <= max; i++)
            {
                MailBee.Mime.MailMessage msg = pop3.DownloadEntireMessage(i);
            
                Console.WriteLine("From: " + msg.From.ToString());
                Console.WriteLine("Subject: " + msg.Subject);
                Console.WriteLine(msg.BodyPlainText);
                Console.WriteLine("---------------------------------");
            
                pop3.DeleteMessage(i);
            }
            
            if (pop3.IsConnected)
                pop3.Disconnect();
        }

 

GmailなどでIMAPを使用する場合は、こんな感じになります。

 
        static void Main(string[] args)
        {
            MailBee.ImapMail.Imap.LicenseKey = "ライセンスキー";
            MailBee.ImapMail.Imap imap = new MailBee.ImapMail.Imap();
            
            imap.Connect("imap.gmail.com");
            imap.Login("アカウント@gmail.com", "パスワード");
            
            imap.SelectFolder("Inbox");
            
            for (int i = 1, max = imap.MessageCount; i <= max; i++)
            {
                MailBee.Mime.MailMessage msg = imap.DownloadEntireMessage(i, false);
            
                Console.WriteLine("From: " + msg.From.ToString());
                Console.WriteLine("Subject: " + msg.Subject);
                Console.WriteLine(msg.BodyPlainText);
                Console.WriteLine("---------------------------------");
            }
            
            if (imap.IsConnected)
                imap.Disconnect();
        }

MailBee.NET Objects は、SMTP、POP3、IMAPなどを含んだメールコンポーネントです。

MailBee.NET Objects
http://www.afterlogic.com/products/net-email-components

MailBee.NET をインストールすると、サンプル(C#, VB)もインストールされるので簡単に動作確認なども行えます。

ただ、サンプルのままでは、携帯などに日本語を含んだメールを送ると、やはり文字化けが起こる可能性がありますので、「Content-Transfer-Encoding"」と「Charset」を指定する必要があります。

        static void Main(string[] args)
        {
            MailBee.SmtpMail.Smtp.LicenseKey = "ライセンスキー";
            
            MailBee.SmtpMail.Smtp smtp = new MailBee.SmtpMail.Smtp();
            smtp.Message.From.AsString = "送信者のメールアドレス";
            smtp.Message.To.AsString = "受取人のメールアドレス";
            smtp.Message.Subject = "サブジェクト";
            smtp.Message.BodyPlainText = "本文";
            
            // 「Content-Transfer-Encoding"」と「Charset」を指定
            smtp.Message.MailTransferEncodingPlain = MailBee.Mime.MailTransferEncoding.Raw7bit;
            smtp.Message.Charset = "iso-2022-jp";
            
            smtp.SmtpServers.Add("SMTPサーバーアドレス");
            smtp.Send();

        }

GmailなどTLSを使用する場合は、こんな感じになります。

        static void Main(string[] args)
        {

            MailBee.SmtpMail.Smtp.LicenseKey = "ライセンスキー";
            
            MailBee.SmtpMail.Smtp smtp = new MailBee.SmtpMail.Smtp();
            smtp.Message.From.AsString = "アカウント@gmail.com";
            smtp.Message.To.AsString = "受取人のメールアドレス";
            smtp.Message.Subject = "サブジェクト";
            smtp.Message.BodyPlainText = "本文";
            
            // 「Content-Transfer-Encoding"」と「Charset」を指定
            smtp.Message.MailTransferEncodingPlain = MailBee.Mime.MailTransferEncoding.Raw7bit;
            smtp.Message.Charset = "iso-2022-jp";
            
            MailBee.SmtpMail.SmtpServer server = new MailBee.SmtpMail.SmtpServer();
            server.Name = "smtp.gmail.com";
            server.SslMode = MailBee.Security.SslStartupMode.UseStartTls;
            server.Port = 587;
            server.AuthMethods = MailBee.AuthenticationMethods.Auto;
            server.AuthOptions = MailBee.AuthenticationOptions.PreferSimpleMethods;
            server.AccountName = "アカウント@gmail.com";
            server.Password = "パスワード";
            
            smtp.SmtpServers.Add(server);
            smtp.Send();

        }

 

MailBee.NET は、NET1.1/2.0/3.0/3.5/4や.NET Compact Framework2.0/3.5と多くの.NET frameworksのバージョンに対応しています。

SmtpClientで問題がある場合など、試用も出来るので MailBee.NET を試してみてはいかがでしょうか?

C# 4.0 で 名前付き引数と省略可能な引数が追加されました。

省略可能な引数では、既定値を指定することによって引数を省略することができ、名前付き引数では、引数名を付けることによって引数の順番を変えることができますので、下記のような感じで使うことができます。

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Hoge());
            Console.WriteLine(Hoge(x: 1));
            Console.WriteLine(Hoge(y: 2));
            Console.WriteLine(Hoge(y: 2, x: 1));

            Console.ReadLine();
        }

        static string Hoge(int x = 0, int y = 0)
        {
            return string.Format("{0}, {1}", x, y);
        }
    }

 結果

20100531

 参考

名前付き引数と省略可能な引数 (C# プログラミング ガイド)
http://msdn.microsoft.com/ja-jp/library/dd264739%28VS.100%29.aspx

LINQ to Twitter を使って、投稿、削除、検索します。

投稿は UpdateStatus メゾットを使用します。

using System;
using System.Collections.Generic;
using System.Linq;
using LinqToTwitter;

class Program
{
	static void Main(string[] args)
	{
		ITwitterAuthorization auth = new UsernamePasswordAuthorization() 
		{ 
			UserName = "USERNAME", 
			Password = "PASSWORD" 
		};
		using (TwitterContext twitterCtx = new TwitterContext(auth, "https://twitter.com/", "http://search.twitter.com/"))
		{
			auth.SignOn();

			// 投稿する
			var tweet = twitterCtx.UpdateStatus("投稿する内容です");

			auth.SignOff();
			Console.ReadLine();
		}
	}
}

削除は DestroyStatus メゾットを使用します。下記コードは、投稿内容が「テスト」となっているものを削除しています。

var tweets = from tweet in twitterCtx.Status
	where tweet.Type == StatusType.Friends && 
		tweet.Text == "テスト"
	select tweet;

foreach (var tweet in tweets)
{
	var status = twitterCtx.DestroyStatus(tweet.StatusID);
}

検索は、Search メゾットを使用します。下記コードは、検索キーワード「ff13」で最初の3件を取得しています。

var queryResults = from search in twitterCtx.Search
	where search.Type == SearchType.Search &&
		search.Query == "ff13" &&
		search.Page == 1 &&
		search.PageSize == 3
		select search;

foreach (var search in queryResults)
{
	Console.WriteLine("Query: " + search.Query);
	Console.WriteLine();

	foreach (var entry in search.Entries)
	{
		Console.WriteLine("AuthorName: " + entry.Author.Name);
		Console.WriteLine("AuthorURI : " + entry.Author.URI);
		Console.WriteLine("Content   : " + entry.Content);
		Console.WriteLine("Published : " + entry.Published);
		Console.WriteLine();
	}
}

今回もLINQ to Twitterを使って、自分のタイムラインを取得します。

前回、ユーザー名とパスワードでの認証したので、今回は認証にOAuthを使用していますが、LinqToTwitterDemo の InitializeOAuthConsumerStrings をそのまま使用しているだけです。

準備

1.「Applications Using Twitter」にアクセスし、「Register a new application ≫」をクリックしてアプリケーションを登録します。

2.アプリケーションの内容を適当に入力して、今回はコンソールアプリでテストしますので「Application Type」は「Client」を選択し、「保存する」をクリックします。

3.「Consumer key」と「Consumer secret」が表示されるのでメモっておきます。

4.プロジェクトを作成し、「LinqToTwitter.dll」を参照に追加します。

5.アプリケーション構成ファイル(App.Config)を作成し、取得した「Consumer key」と「Consumer secret」を設定に追加します。

app.config

<configuration>
  <appSettings>
    <add key="twitterConsumerKey" value="[Consumer key]" />
    <add key="twitterConsumerSecret" value="[Consumer secret]" />
  </appSettings>
</configuration>

 

サンプルコード(C#)

using System;
using System.Linq;
using LinqToTwitter;
using System.Configuration;

class Program
{
    // 認証
    private static void InitializeOAuthConsumerStrings(TwitterContext twitterCtx)
    {
        var oauth = (DesktopOAuthAuthorization)twitterCtx.AuthorizedClient;
        oauth.GetVerifier = () =>
        {
            Console.WriteLine("Next, you'll need to tell Twitter to authorize access.\nThis program will not have access to your credentials, which is the benefit of OAuth.\nOnce you log into Twitter and give this program permission,\n come back to this console.");
            Console.Write("Please enter the PIN that Twitter gives you after authorizing this client: ");
            return Console.ReadLine();
        };

        if (oauth.CachedCredentialsAvailable)
        {
            Console.WriteLine("Skipping OAuth authorization step because that has already been done.");
        }
    }

    static void Main(string[] args)
    {
        ITwitterAuthorization auth = new DesktopOAuthAuthorization();
        TwitterContext twitterCtx = new TwitterContext(auth, "https://twitter.com/", "http://search.twitter.com/");

        InitializeOAuthConsumerStrings(twitterCtx);

        auth.SignOn();

        // タイムラインを取得して出力
        var tweets = from tweet in twitterCtx.Status
                     where tweet.Type == StatusType.Friends
                     select tweet;

        foreach (var tweet in tweets)
        {
            Console.WriteLine("User Name: {0}, Tweet: {1}",
                tweet.User.Name,
                tweet.Text);
        }

        twitterCtx.Dispose();

        Console.ReadLine();
    }
}

 

実行

1.初回実行時にブラウザが起動し、「ユーザー名やメールアドレス」と「パスワード」の入力ページが表示されますので、入力して「許可する」をクリックします。

201s

2. ページが移動して番号が表示されますので、表示された番号をコンソールに入力します。

202s

203s

3.認証が通ればタイムラインを取得しコンソールに出力されます。