C#: Outlook経由でメールを送る方法
C#でOutlook経由でメールを送る方法です。
Microsoft.Office.Interop.Outlook
ライブラリを使います。
このライブラリはダウンロード必要なのですが、以下の記事を参考にダウンロードしてください。
この記事はMicrosoft.Office.Interop.Excel
ライブラリの導入法ですが、解凍した同じフォルダ内にMicrosoft.Office.Interop.Outlook
ライブラリもあります。
メールを送るソースコードはこちらです。
//using Outlook = Microsoft.Office.Interop.Outlook; var app = new Outlook.Application(); Outlook.MailItem mail = app.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem; mail.Subject = "C#からテストメール"; Outlook.AddressEntry currentUser = app.Session.CurrentUser.AddressEntry; mail.Body = "このメールはC#からのテストメールです。"; mail.Recipients.Add("xxx@outlook.jp"); mail.Recipients.ResolveAll(); mail.Send();
コンパイルの際はライブラリを参照させる必要があります。Visual Studioを使っている人が多いと思いますが、その方法はググってください。
僕自身はcscで手動コンパイルなので以下のように/reference:
オプションで参照させています。
csc.exe /platform:x86 /reference:Microsoft.Office.Interop.Outlook.dll outlookTest.cs
コンパイル後、実行してみるとご覧の通りメールが送信されました。
[ad#top-1]
Formを使って簡単なメール送信ソフトを作ってみる
こんな感じの簡単なフォームからメール送信してみます。
こちらがソースコード全文です。
using System; using System.Drawing; using System.Windows.Forms; using System.Collections.Generic; using Outlook = Microsoft.Office.Interop.Outlook; class outlookTest{ static void Main(string[] args){ Application.Run(new MainWindow(args)); } } class MainWindow : Form{ private TextBox textBox; public MainWindow(string[] args){ this.StartPosition = FormStartPosition.CenterScreen; this.Width = 400; this.Height =300; this.Text = "テキストボックステスト"; textBox = new TextBox(){ Location = new Point(5, 5), Size = new Size(300, 150), Multiline = true, Parent=this, }; Button btn1 = new Button(){ Text = "OK", Location = new Point(5, 200), Parent = this, }; btn1.Click += new EventHandler(BtnClicked); } private void BtnClicked(object sender, EventArgs e){ var app = new Outlook.Application(); Outlook.MailItem mail = app.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem; mail.Subject = "C#からテストメール"; Outlook.AddressEntry currentUser = app.Session.CurrentUser.AddressEntry; mail.Body = textBox.Text; mail.Recipients.Add("xxx@outlook.jp"); mail.Recipients.ResolveAll(); mail.Send(); } }
こちらが送られてきたメールです。うまく行きました。
[ad#ad-1]
スポンサーリンク