天天看点

使用c#给outlook添加任务、发送邮件

    c#在使用outlook提供的一些API时,需要将outlook相关的com引用到项目中。 具体方法就是用vs打开工程后,在工程上添加引用,在com选项卡上,选择Microsoft Outlook 12.0 Object Library,如果安装的不是outlook2007,则对应com的版本不一样。注意下面描述的方法是在命令行模式或者winform模式下的,不是web模式下的。 在web模式下使用的方法稍有不同,不在此处讨论。 

    给outlook添加任务,代码如下:

        /// <summary>

        /// 给outlook添加一个新的任务

        /// </summary>

        /// <param name="subject">新任务标题</param>

        /// <param name="body">新任务正文</param>

        /// <param name="dueDate">新任务到期时间</param>

        /// <param name="importance">新任务优先级</param>

        public static void AddNewTask(string subject, string body, DateTime dueDate, OlImportance importance)

        {

            try

            {

                Application outLookApp = new Application();

                TaskItem newTask = (TaskItem)outLookApp.CreateItem(OlItemType.olTaskItem);

                newTask.Body = body;

                newTask.Subject = subject;

                newTask.Importance = importance;

                newTask.DueDate = dueDate;

                newTask.Save();

            }

            catch(System.Exception e)

                throw e;

        }

最简单的发送邮件    下面是一个最简单的发送邮件的例子,在该例子中,只能给一个邮箱地址发邮件,而且还不能够添加附件。代码如下:

        /// 一个最简单的发送邮件的例子。同步方式。只支持发送到一个地址,而且没有附件。

        /// <param name="server">smtp服务器地址</param>

        /// <param name="from">发送者邮箱</param>

        /// <param name="to">接收者邮箱</param>

        /// <param name="subject">主题</param>

        /// <param name="body">正文</param>

        /// <param name="isHtml">正文是否以html形式展现</param>

        public static void SimpleSeedMail(string server, string from, string to, string subject, string body, bool isHtml)

                MailMessage message = new MailMessage(from, to, subject, body);

                message.IsBodyHtml = isHtml;

                SmtpClient client = new SmtpClient(server);

                client.Credentials = new NetworkCredential("发送者邮箱用户名(即@前面的东东)","发送者邮箱密码");

                client.Send(message);

            catch (System.Exception e)

向多人发邮件,并支持发送多个附件    代码如下:

        /// 支持向多人发邮件,并支持多个附件的一个发送邮件的例子。

        /// <param name="to">接收者邮箱,多个接收者以;隔开</param>

        /// <param name="subject">邮件主题</param>

        /// <param name="body">邮件正文</param>

        /// <param name="mailAttach">附件</param>

        /// <param name="isHtml">邮件正文是否需要以html的方式展现</param>

        public static void MultiSendEmail(string server, string from, string to, string subject, string body, ArrayList mailAttach, bool isHtml)

            MailMessage eMail = new MailMessage();

            SmtpClient eClient = new SmtpClient(server);

            eClient.Credentials = new NetworkCredential("发送者邮箱用户名(即@前面的东东)", "发送者邮箱密码");

            eMail.Subject = subject;

            eMail.SubjectEncoding = Encoding.UTF8;

            eMail.Body = body;

            eMail.BodyEncoding = Encoding.UTF8;

            eMail.From = new MailAddress(from);

            string[] arrMailAddr;

                #region 添加多个收件人

                eMail.To.Clear();

                if (!string.IsNullOrEmpty(to))

                {

                    arrMailAddr = to.Split(';');

                    foreach (string strTo in arrMailAddr)

                    {

                        if (!string.IsNullOrEmpty(strTo))

                        {

                            eMail.To.Add(strTo);

                        }

                    }

                }

                #endregion

                #region 添加多个附件

                eMail.Attachments.Clear();

                if (mailAttach != null)

                    for (int i = 0; i < mailAttach.Count; i++)

                        if (!string.IsNullOrEmpty(mailAttach[i].ToString()))

                            eMail.Attachments.Add(new System.Net.Mail.Attachment(mailAttach[i].ToString()));

                #region 发送邮件

                eClient.Send(eMail);

        }//end of method

异步发送邮件的一个例子。以163的smtp服务器为例。    代码如下:

using System;

using System.Net;

using System.Net.Mail;

using System.Net.Mime;

using System.Threading;

using System.ComponentModel;

namespace Examples.SmptExamples.Async

{

    public class SimpleAsynchronousExample

    {

        static bool mailSent = false;

        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)

            // Get the unique identifier for this asynchronous operation.

            String token = (string)e.UserState;

            if (e.Cancelled)

                Console.WriteLine("[{0}] Send canceled.", token);

            if (e.Error != null)

                Console.WriteLine("[{0}] {1}", token, e.Error.ToString());

            else

                Console.WriteLine("Message sent.");

            mailSent = true;

        public static void Main(string[] args)

            SmtpClient client = new SmtpClient("smtp.163.com");

            client.Credentials = client.Credentials = new NetworkCredential("发送者邮箱用户名", "发送者邮箱密码");

            MailAddress from = new MailAddress("[email protected]");

            MailAddress to = new MailAddress("[email protected]");

            MailMessage message = new MailMessage(from, to);

            message.Body = "这是一封测试异步发送邮件的邮件 ";

            message.BodyEncoding = System.Text.Encoding.UTF8;

            message.Subject = "测试异步发邮件";

            message.SubjectEncoding = System.Text.Encoding.UTF8;

            // 设置回调函数

            client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

            // SendAsync方法的第二个参数可以是任何对象,这里使用一个字符串标识本次发送

            //传入的该对象可以在邮件发送结束触发的回调函数中访问到。

            string userState = "test message1";

            client.SendAsync(message, userState);

            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");

            string answer = Console.ReadLine();

            if (answer.StartsWith("c") && mailSent == false)

                client.SendAsyncCancel();

            //清理工作

            message.Dispose();

            Console.WriteLine("Goodbye.");

            Console.ReadLine();

    }

}