C#调用本地Outlook发送邮件实例

创建一个新的winform,在winform中添加一个button,如下:


双击SendMail按钮,添加如下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Outlook.Application olApp = new Outlook.Application();
            Outlook.MailItem mailItem = (Outlook.MailItem)olApp.CreateItem(Outlook.OlItemType.olMailItem);
            mailItem.To = "xxxxxxxxx@xxx.com";
            mailItem.Subject = DateTime.Now.ToString("yyyyMMdd") + "_报表";
            mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;

            string content = "附件为" + DateTime.Now.ToString("yyyyMMdd") + " 数据,请查阅,谢谢!";
            content = "各收件人,<br/> <br/>请重点关注以下内容:<br/> <br/>" + content + "<br/> <br/><br/><br/>此邮件为系统自动邮件通知,请不要直接进行回复!谢谢。";
            content = content + "<br/>\r\n                                    <br/>Best Regards!\r\n                                    <br/>\r\n                                    <br/>          \r\n                                    <br/>==============================================\r\n                               \r\n                                    <br/>\r\n                                    <br/>\r\n                \r\n             ===============================================";


            mailItem.HTMLBody = content;
            mailItem.Attachments.Add(@"C:\test.rar");
            ((Outlook._MailItem)mailItem).Send();
            mailItem = null;
            olApp = null;
        }
        
    }
}


其中引用了using Outlook = Microsoft.Office.Interop.Outlook; 需要在Reference里添加如下库:



在执行前修改收件人邮箱地址和附件地址:

mailItem.To = "xxxxxxxxx@xxx.com";
mailItem.Attachments.Add(@"C:\test.rar");
(由于没有添加判断附件的语句,所以没有找到附件时不会发送邮件。)


完成后按F5执行,点击button,接收邮件如下:



具体使用过程中可根据需要调整邮件内容和是否添加附件等。

参考:http://www.cnblogs.com/allen0118/p/4622798.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值