0
2

More than 3 years have passed since last update.

Outlookのメール作成・取得をC#でやってみる - Visual Studio不使用 - 自分用メモ

Last updated at Posted at 2020-07-14

ひな形ではやれないような、柔軟なテンプレメールの作成とか、
使いづらいメール検索機能とかを何とかしたい。(「高度な検索」使うのめんどい)
というわけで手掛かりレベルのものを残してみた。。

詳細は参考サイト参照ください・・

コンパイルバッチ

OutlookのバージョンやWindowsのバージョンによっては微妙に違うフォルダにいるかもです。

compile.bat

csc ^
 /r:C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Outlook\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Outlook.dll ^
 /r:C:\Windows\assembly\GAC_MSIL\office\15.0.0.0__71e9bce111e9429c\Office.dll ^
 %*

コンパイル方法

csc.exeのパスは事前に通しておく必要あり。
自分の環境では下記にいました。
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe


compile.bat OutlookMailFinder.cs

ソース

Outlook起動済みで使う前提で作っています。
new Outlook.Application()を使えば起動させることも可能。

OutlookMailFinder.cs

using System;
using System.Drawing;
//using System.Collections.Generic;
//using System.Reflection;
using System.Runtime.CompilerServices; // to use [MethodImpl(MethodImplOptions.NoInlining)]
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using Outlook = Microsoft.Office.Interop.Outlook;


class OutlookMailFinder : Form
{
    TextBox txtSenderMailAddress;
    Button btnStartTryGet;


    [MethodImpl(MethodImplOptions.NoInlining)]
    void LaunchSendMail()
    {
        Outlook.Application oOutlookApp = null;
        try {
            oOutlookApp = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
        }
        catch ( COMException ) { // COMException封殺するのはあまりお勧めしない・・
            Console.WriteLine("Cannot found active Outlook application");
            //oOutlookApp = new Outlook.Application();
            return;
        }

        var mailItem = (Outlook.MailItem)oOutlookApp.CreateItem(Outlook.OlItemType.olMailItem);
        if (mailItem != null)
        {                
            Outlook.Recipient to = mailItem.Recipients.Add("XXX@XXX.co.jp");
            to.Type = (int)Outlook.OlMailRecipientType.olTo;

            Outlook.Recipient cc;
            cc = mailItem.Recipients.Add("YYY@YYY.co.jp");
            cc.Type = (int)Outlook.OlMailRecipientType.olCC;

            cc = mailItem.Recipients.Add("ZZZ@ZZZ.co.jp");
            cc.Type = (int)Outlook.OlMailRecipientType.olCC;

            // アドレス帳の表示名で表示できる
            mailItem.Recipients.ResolveAll();

            mailItem.Subject = "件名";
            mailItem.Body = "本文";
    
            // 表示(Displayメソッド引数のtrue/falseでモーダル/モードレスウィンドウを指定して表示できる)
            mailItem.Display(false);
        }
    }


    [MethodImpl(MethodImplOptions.NoInlining)]
    void GetMails()
    {
        Outlook.Application oOutlookApp = null;
        try {
            oOutlookApp = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
        }
        catch ( COMException ) { // COMException封殺するのはあまりお勧めしない・・
            Console.WriteLine("Cannot found active Outlook application");
            //oOutlookApp = new Outlook.Application();
            return;
        }

        var folder = oOutlookApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
//      var mapiFolders = oOutlookApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Folders;

//      foreach(Outlook.Folder folder in mapiFolders)
        {
            Console.WriteLine(folder.Name);


            foreach(Outlook.MailItem mail in folder.Items)
            {
                //ヘッダー・送信者アドレス・題名・本文を取得
                //Console.WriteLine(mail.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E"));
                Console.WriteLine(mail.SenderEmailAddress);
                Console.WriteLine(mail.Subject);
                // Console.WriteLine(mail.Body);

                GC.Collect();
                GC.WaitForPendingFinalizers();
                // GC入れないと下記で落ちる場合がある
                //System.Runtime.InteropServices.COMException (0x9077000E): メモリまたはシステム リソースが不足しています。いくつかのウィンドウまたはプログラムを終了してから、再度実行してください。
                //   場所 Microsoft.Office.Interop.Outlook._MailItem.get_SenderEmailAddress()
            }
        }
    }

    OutlookMailFinder()
    {

        Controls.Add(txtSenderMailAddress = new TextBox(){
            Location = new Point(0,0),
            Width = 150
        });


        Controls.Add(btnStartTryGet = new Button(){
            Text = "Get",
            Location = new Point(180, 0),
            Width = 100
        });
        btnStartTryGet.Click += (s,e)=>{
            // GetMails();
            LaunchSendMail();
        };


        Load      += (s,e)=>{MyResize();};
        Resize    += (s,e)=>{MyResize();};
        ResizeEnd += (s,e)=>{MyResize();};

    }

    void MyResize()
    {
        /*
        int w = ClientSize.Width;
        int h = ClientSize.Height;// - txtContent.Top;
        if(w<50){w=50;}
        if(h<50){h=50;}
        txtContent.Size = new Size(w,h);
        */
    }

    [STAThread]
    static void Main(string[] args)
    {
        Application.Run(new OutlookMailFinder());
    }
}

参考サイト

0
2
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
0
2