关山明月

导航

C#调用Outlook来发送邮件

     写了一个简单的Windows Form程序,实现利用Outlook来发送电子邮件的功能。下面逐步讲解如何实现,再加上具体的代码。

  1. 打开VS2010, 新建一个Windows Form程序。
  2. 右击工程文件的Reference,选择Add Reference。
  3. 点击Com tab, 选择Microsoft.Office.Interop.Outlook.dll,点击 OK。
  4. 添加引用: using Outlook = Microsoft.Office.Interop.Outlook;
  5. 其它的就不说了,直接上代码了。

 

View Code
 1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9 using Outlook = Microsoft.Office.Interop.Outlook;
10
11 namespace SendMailByOutlook
12 {
13 public partial class Form1 : Form
14 {
15 public Form1()
16 {
17 InitializeComponent();
18 }
19
20 private void button1_Click(object sender, EventArgs e)
21 {
22 Outlook.Application olApp = new Outlook.Application();
23 Outlook.MailItem mailItem = (Outlook.MailItem)olApp.CreateItem(Outlook.OlItemType.olMailItem);
24 mailItem.To = "xyz@hotmail.com";
25 mailItem.Subject = "A test";
26 mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
27 mailItem.HTMLBody = "Hello world";
28 ((Outlook._MailItem)mailItem).Send();
29
30 mailItem = null;
31 olApp = null;
32 MessageBox.Show("Mail has been sent successfully!");
33
34
35 }
36 }
37 }


    最后,点击Send,提示发送邮件成功!

    还有一点需要注意,就是说调用Outlook来发送邮件时,Outlook必须要开启。否则,该程序会抛出异常。大家有什么更好的办法,欢迎交流!

       

posted on 2011-10-20 22:07  关山明月  阅读(2567)  评论(0编辑  收藏  举报