创建一个新的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;
}
}
}
在执行前修改收件人邮箱地址和附件地址:
mailItem.To = "xxxxxxxxx@xxx.com";
mailItem.Attachments.Add(@"C:\test.rar");
(由于没有添加判断附件的语句,所以没有找到附件时不会发送邮件。)
完成后按F5执行,点击button,接收邮件如下:
具体使用过程中可根据需要调整邮件内容和是否添加附件等。