LoginSignup
4
3

More than 5 years have passed since last update.

デフォルトメーラーの定義されている場所

Last updated at Posted at 2013-06-20

はじめに

要約

Webページ上のmailtoリンクを押したときに、「規定のプログラム」で指定したメーラーが呼び出されます。
このメーラーのパスをレジストリから取得する方法を記述します。
なお、ここに書いてある情報は環境により左右される部分が大きいと思いますので、ご注意下さい。
OS: Windows8 Pro 64bit

背景

基本的に@ITの記事[1]をベースにしています。ただ、ここにあるHKEY_CLASSES_ROOT\mailto\shell\open\commandを書き換えてくれないメーラーがあるようなので(←Becky)、アレンジを加えたという形です。

方法

説明

アプリケーション名の取得

MSDN[2]によると、デフォルトのメーラーは次のいずれかで定義することになっています。
* HKEY_CURRENT_USER\SOFTWARE\Clients\Mail
* HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail
ここに書いてある意味が正しく理解できていないのですが、実際に中身を見てみると、HKCUが規定のプログラムのアプリケーション名を保持していたので、こちらを使うことにします。

アプリケーションのパスの取得

mailto:で実行されるコマンドは次の場所にあります。
HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail\(アプリ名)\Protocols\mailto\shell\open\command

実装

実装は次の通りです。getExePath()は@IT[1]のコピペなので、詳しくはリンク元を見て下さい。

#
// using省略
using Microsoft.Win32; // Registry, RegistryKeyクラスを使うのに必要

public static string GetDefaultMailerExePath()
{
    try
    {
        // デフォルトメーラーのアプリケーション名を取得
        string name = (string)Registry.CurrentUser
                .OpenSubKey(@"Software\Clients\Mail").GetValue(String.Empty);

        // デフォルトメーラーがmailto:を受け付けたときのコマンドを取得
        string exe = @"SOFTWARE\Clients\Mail\" + name 
                + @"\Protocols\mailto\shell\open\command";

        string command = (string)Registry.LocalMachine
               .OpenSubKey(exe).GetValue(String.Empty);

        // デフォルトメーラーのexeパスを取得
        return getExePath(command);
    }
    catch (NullReferenceException)
    {
        throw new Exception("デフォルトメーラーのパスを取得できませんでした");
    }
}

private static string getExePath(string command)
{
    string path = "";

    // 前後の余白を削る
    command = command.Trim();
    if (command.Length == 0)
    {
        return path;
    }

    // 「"」で始まる長いパス形式かどうかで処理を分ける
    if (command[0] == '"')
    {
        // 「"~"」間の文字列を抽出
        int endIndex = command.IndexOf('"', 1);
        if (endIndex != -1)
        {
            // 抽出開始を「1」ずらす分、長さも「1」引く
            path = command.Substring(1, endIndex - 1);
        }
    }
    else
    {
        // 「(先頭)~(スペース)」間の文字列を抽出
        int endIndex = command.IndexOf(' ');
        if (endIndex != -1)
        {
            path = command.Substring(0, endIndex);
        }
        else
        {
            path = command;
        }
    }
    return path;
}

補足

元ネタのアレンジということで書きましたが、mailtoではなくアプリケーションを開くためのコマンドを使った方が直接的かなと思います。これは次のレジストリに格納されています。

HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail\(アプリ名)\shell\open\command

参考

[1] 既定のブラウザ/メーラの.EXEファイル・パスを取得するには?[C#、VB]
[2] How to Register an Internet Browser or Email Client With the Windows Start Menu (MSDN)
http://msdn.microsoft.com/en-us/library/windows/desktop/dd203067(v=vs.85).aspx
のHow the Start Menu Displays the Default Email Clientの項目

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3