转载自 http://blog.163.com/china__xuhua/blog/static/199723169201243010111517/
1、功能简介
本实例实现了邮件、附件的发送。支持:1、一对多,即支持可以同时对多个用户发送邮件;2、支持可以同时发送多个附件。
2、页面效果图
3、后台代码:
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.IO;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
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.IO;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
namespace SmtpEmail
{
public partial class Form1 : Form
{
#region 构造函数
public Form1()
{
InitializeComponent();
}
#endregion
{
public partial class Form1 : Form
{
#region 构造函数
public Form1()
{
InitializeComponent();
}
#endregion
#region 收件邮箱地址
//邮箱地址添加到GridView中
private void btnEmailAdd_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(this.txtEamilFrom.Text.Trim()))
{
if (this.txtEamilFrom.ForeColor == Color.Red)
{
MessageBox.Show("输入的收件箱格式不正确!");
}
else
{
int vRownumber = this.grdEmails.Rows.Add();
this.grdEmails.Rows[vRownumber].Cells[0].Value = this.txtEamilFrom.Text.Trim();
this.txtEamilFrom.Text = string.Empty;
}
}
}
//邮箱地址添加到GridView中
private void btnEmailAdd_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(this.txtEamilFrom.Text.Trim()))
{
if (this.txtEamilFrom.ForeColor == Color.Red)
{
MessageBox.Show("输入的收件箱格式不正确!");
}
else
{
int vRownumber = this.grdEmails.Rows.Add();
this.grdEmails.Rows[vRownumber].Cells[0].Value = this.txtEamilFrom.Text.Trim();
this.txtEamilFrom.Text = string.Empty;
}
}
}
//邮箱地址 删除
private void btnRemove_Click(object sender, EventArgs e)
{
if (this.grdEmails.Rows.Count > 0)
{
//只可选中一条,进行删除
//int vCurrentIndex = this.grdEmails.CurrentRow.Index;
//this.grdEmails.Rows.RemoveAt(vCurrentIndex);
private void btnRemove_Click(object sender, EventArgs e)
{
if (this.grdEmails.Rows.Count > 0)
{
//只可选中一条,进行删除
//int vCurrentIndex = this.grdEmails.CurrentRow.Index;
//this.grdEmails.Rows.RemoveAt(vCurrentIndex);
//支持多选删除
foreach (DataGridViewRow vrow in grdEmails.SelectedRows)
{
int vIndex = vrow.Index;
this.grdEmails.Rows.RemoveAt(vIndex);
}
foreach (DataGridViewRow vrow in grdEmails.SelectedRows)
{
int vIndex = vrow.Index;
this.grdEmails.Rows.RemoveAt(vIndex);
}
}
}
}
//邮箱地址 清空
private void btnClear_Click(object sender, EventArgs e)
{
this.grdEmails.Rows.Clear();
}
#endregion
private void btnClear_Click(object sender, EventArgs e)
{
this.grdEmails.Rows.Clear();
}
#endregion
#region 验证邮箱输入是否正确,不正确是,字体显示为红色
//验证 发件邮箱是否正确
private void txtEmailTo_Leave(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(this.txtEmailTo.Text.Trim()))
{
bool a = IsEmail(this.txtEmailTo.Text);
//如果不为 邮箱,字体变为红色
if (IsEmail(this.txtEmailTo.Text.Trim()) == false)
{
this.txtEmailTo.ForeColor = Color.Red;
}
else
{
this.txtEmailTo.ForeColor = Color.Black;
}
}
}
//验证 发件邮箱是否正确
private void txtEmailTo_Leave(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(this.txtEmailTo.Text.Trim()))
{
bool a = IsEmail(this.txtEmailTo.Text);
//如果不为 邮箱,字体变为红色
if (IsEmail(this.txtEmailTo.Text.Trim()) == false)
{
this.txtEmailTo.ForeColor = Color.Red;
}
else
{
this.txtEmailTo.ForeColor = Color.Black;
}
}
}
private bool IsEmail(string vEmail)
{
return System.Text.RegularExpressions.Regex.IsMatch(vEmail, @"^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$");
}
{
return System.Text.RegularExpressions.Regex.IsMatch(vEmail, @"^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$");
}
//验证 受件箱邮箱是否正确
private void txtEamilFrom_Leave(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(this.txtEamilFrom.Text.Trim()))
{
bool a = IsEmail(this.txtEamilFrom.Text);
//如果不为 邮箱,字体变为红色
if (IsEmail(this.txtEamilFrom.Text.Trim()) == false)
{
this.txtEamilFrom.ForeColor = Color.Red;
}
else
{
this.txtEamilFrom.ForeColor = Color.Black;
}
}
}
#endregion
private void txtEamilFrom_Leave(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(this.txtEamilFrom.Text.Trim()))
{
bool a = IsEmail(this.txtEamilFrom.Text);
//如果不为 邮箱,字体变为红色
if (IsEmail(this.txtEamilFrom.Text.Trim()) == false)
{
this.txtEamilFrom.ForeColor = Color.Red;
}
else
{
this.txtEamilFrom.ForeColor = Color.Black;
}
}
}
#endregion
#region 参数
private string [] Files;//保存 附件文件路径
private SmtpClient vSmtpClient = null;//设置SMTP协议
private MailAddress vMailAddressFrom = null;//设置发件人地址,需要密码
private MailAddress vMailAddressTo = null;//设置收件人地址,不需要密码
private FileStream vFileStream = null;//附件文件流vMailAddressFrom
private MailMessage vMailMessage = null;
private string [] Files;//保存 附件文件路径
private SmtpClient vSmtpClient = null;//设置SMTP协议
private MailAddress vMailAddressFrom = null;//设置发件人地址,需要密码
private MailAddress vMailAddressTo = null;//设置收件人地址,不需要密码
private FileStream vFileStream = null;//附件文件流vMailAddressFrom
private MailMessage vMailMessage = null;
#endregion
#region 选择文件(支持多选,可以同时上传多个附件)
private void btnFileSelect_Click(object sender, EventArgs e)
{
OpenFileDialog vOpenSelectFile = new OpenFileDialog();
vOpenSelectFile.Multiselect = true;
vOpenSelectFile.Filter = "全部文件|*.*|Excel文件|*.xlsx;*.xls|Csv文件|*.csv";
vOpenSelectFile.FilterIndex = 2;
vOpenSelectFile.RestoreDirectory = true;
if (vOpenSelectFile.ShowDialog() == DialogResult.OK)
{
this.txtFile.Text = vOpenSelectFile.FileNames[0].ToString();
Files = new string[vOpenSelectFile.FileNames.Length];//实例化 Files,用以保存文件附近信息
for (int i = 0; i < vOpenSelectFile.FileNames.Length; i++)
{
Files[i] = vOpenSelectFile.FileNames[i].ToString();
}
}
}
#endregion
#region 选择文件(支持多选,可以同时上传多个附件)
private void btnFileSelect_Click(object sender, EventArgs e)
{
OpenFileDialog vOpenSelectFile = new OpenFileDialog();
vOpenSelectFile.Multiselect = true;
vOpenSelectFile.Filter = "全部文件|*.*|Excel文件|*.xlsx;*.xls|Csv文件|*.csv";
vOpenSelectFile.FilterIndex = 2;
vOpenSelectFile.RestoreDirectory = true;
if (vOpenSelectFile.ShowDialog() == DialogResult.OK)
{
this.txtFile.Text = vOpenSelectFile.FileNames[0].ToString();
Files = new string[vOpenSelectFile.FileNames.Length];//实例化 Files,用以保存文件附近信息
for (int i = 0; i < vOpenSelectFile.FileNames.Length; i++)
{
Files[i] = vOpenSelectFile.FileNames[i].ToString();
}
}
}
#endregion
#region 验证页面必填项是否已经完善
private bool CheckPage()
{
if (string.IsNullOrEmpty(this.comServer.Text))
{
MessageBox.Show("请输入SMTP服务器名称","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
return false;
}
else if (string.IsNullOrEmpty(this.numberPort.Value.ToString()))
{
MessageBox.Show("请输入SMTP服务器端口", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else if (string.IsNullOrEmpty(this.txtEmailTo.Text))
{
MessageBox.Show("请输入发件人邮箱地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else if (string.IsNullOrEmpty(this.txtformPwd.Text))
{
MessageBox.Show("请输入发件人邮箱密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else if (this.grdEmails.Rows.Count < 1)
{
MessageBox.Show("请输入收件人邮箱地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else if (string.IsNullOrEmpty(this.txtEmailtitle.Text))
{
MessageBox.Show("请输入邮件标题", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
private bool CheckPage()
{
if (string.IsNullOrEmpty(this.comServer.Text))
{
MessageBox.Show("请输入SMTP服务器名称","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
return false;
}
else if (string.IsNullOrEmpty(this.numberPort.Value.ToString()))
{
MessageBox.Show("请输入SMTP服务器端口", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else if (string.IsNullOrEmpty(this.txtEmailTo.Text))
{
MessageBox.Show("请输入发件人邮箱地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else if (string.IsNullOrEmpty(this.txtformPwd.Text))
{
MessageBox.Show("请输入发件人邮箱密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else if (this.grdEmails.Rows.Count < 1)
{
MessageBox.Show("请输入收件人邮箱地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else if (string.IsNullOrEmpty(this.txtEmailtitle.Text))
{
MessageBox.Show("请输入邮件标题", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
return true;
}
#endregion
}
#endregion
#region 邮件发送
//设置SMTP服务器信息
private void SetSmtpClient(string vServerHost,int vPort)
{
vSmtpClient = new SmtpClient();
vSmtpClient.Host = vServerHost;//SMTP服务器的名称
vSmtpClient.Port = vPort;//指定端口号
vSmtpClient.Timeout = 0;//超时时间
}
private void SetSmtpClient(string vServerHost,int vPort)
{
vSmtpClient = new SmtpClient();
vSmtpClient.Host = vServerHost;//SMTP服务器的名称
vSmtpClient.Port = vPort;//指定端口号
vSmtpClient.Timeout = 0;//超时时间
}
//验证发件人信息
private void SetAddressForm(string vMailAddress, string vMailPwd)
{
//创建服务器认证
NetworkCredential vNetwork = new NetworkCredential(vMailAddress, vMailPwd);
//实例化 发件人地址
vMailAddressFrom = new MailAddress(vMailAddress, "");
//指定发件人信息,包括邮箱地址和邮箱密码
vSmtpClient.Credentials = new NetworkCredential(vMailAddressFrom.Address, vMailPwd);
}
private void SetAddressForm(string vMailAddress, string vMailPwd)
{
//创建服务器认证
NetworkCredential vNetwork = new NetworkCredential(vMailAddress, vMailPwd);
//实例化 发件人地址
vMailAddressFrom = new MailAddress(vMailAddress, "");
//指定发件人信息,包括邮箱地址和邮箱密码
vSmtpClient.Credentials = new NetworkCredential(vMailAddressFrom.Address, vMailPwd);
}
//检测附件大小
private bool Check_File(string vFilePath,out string vInfo)
{
vFileStream = new FileStream(vFilePath, FileMode.Open);
string vFileName = vFileStream.Name;
int vSize = Convert.ToInt32(vFileStream.Length / 1024 / 1024);
vFileStream.Close();
if (vSize > 15)
{
vInfo = "文件名为:" + vFileName + "的文件大小大于15M,允许上传。";
return false;
}
vInfo = string.Empty;
return true;
}
private bool Check_File(string vFilePath,out string vInfo)
{
vFileStream = new FileStream(vFilePath, FileMode.Open);
string vFileName = vFileStream.Name;
int vSize = Convert.ToInt32(vFileStream.Length / 1024 / 1024);
vFileStream.Close();
if (vSize > 15)
{
vInfo = "文件名为:" + vFileName + "的文件大小大于15M,允许上传。";
return false;
}
vInfo = string.Empty;
return true;
}
//发送
private void btnSaveTo_Click(object sender, EventArgs e)
{
if (CheckPage())//必填项验证通过
{
//初始化Smtp服务器信息
SetSmtpClient("Smtp." + this.comServer.Text.Trim(), Convert.ToInt32(this.numberPort.Value));
private void btnSaveTo_Click(object sender, EventArgs e)
{
if (CheckPage())//必填项验证通过
{
//初始化Smtp服务器信息
SetSmtpClient("Smtp." + this.comServer.Text.Trim(), Convert.ToInt32(this.numberPort.Value));
//验证发件邮箱地址和密码
SetAddressForm(this.txtEmailTo.Text.Trim(), this.txtformPwd.Text.Trim());
SetAddressForm(this.txtEmailTo.Text.Trim(), this.txtformPwd.Text.Trim());
vMailMessage = new MailMessage();
//添加收件人邮箱地址
foreach (DataGridViewRow vRow in grdEmails.Rows)
{
vMailAddressTo = new MailAddress(vRow.Cells[0].Value.ToString().Trim());
vMailMessage.To.Add(vMailAddressTo);
}
foreach (DataGridViewRow vRow in grdEmails.Rows)
{
vMailAddressTo = new MailAddress(vRow.Cells[0].Value.ToString().Trim());
vMailMessage.To.Add(vMailAddressTo);
}
//发件人邮箱
vMailMessage.From = vMailAddressFrom;
vMailMessage.From = vMailAddressFrom;
//邮件主题
vMailMessage.Subject = this.txtEmailtitle.Text.Trim();
vMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;//字体使用的编码
vMailMessage.Subject = this.txtEmailtitle.Text.Trim();
vMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;//字体使用的编码
//邮件正文
vMailMessage.Body = this.txtEmailBody.Text.Trim();
vMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
vMailMessage.Body = this.txtEmailBody.Text.Trim();
vMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
//清空历史附件,以防附件重复发送
vMailMessage.Attachments.Clear();
vMailMessage.Attachments.Clear();
//添加附件
for (int i = 0; i < Files.Length; i++)
{
vMailMessage.Attachments.Add(new Attachment(Files[i].Trim().ToString(), MediaTypeNames.Application.Octet));
}
//注册邮件发送完毕后的处理事件
vSmtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
for (int i = 0; i < Files.Length; i++)
{
vMailMessage.Attachments.Add(new Attachment(Files[i].Trim().ToString(), MediaTypeNames.Application.Octet));
}
//注册邮件发送完毕后的处理事件
vSmtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
//开始发送邮件
vSmtpClient.SendAsync(vMailMessage,"000000000");
}
}
vSmtpClient.SendAsync(vMailMessage,"000000000");
}
}
//发送邮件后所处理的函数
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
try
{
if (e.Cancelled)
{
MessageBox.Show("发送已取消!");
}
if (e.Error != null)
{
MessageBox.Show("邮件发送失败!" + " " + "技术信息: " +"请验证,发件邮箱和密码是否正确!"+ e.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("邮件成功发出!", "恭喜!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception Ex)
{
MessageBox.Show("邮件发送失败!" + " " + "技术信息: " + Ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
try
{
if (e.Cancelled)
{
MessageBox.Show("发送已取消!");
}
if (e.Error != null)
{
MessageBox.Show("邮件发送失败!" + " " + "技术信息: " +"请验证,发件邮箱和密码是否正确!"+ e.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("邮件成功发出!", "恭喜!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception Ex)
{
MessageBox.Show("邮件发送失败!" + " " + "技术信息: " + Ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
}
}
}
//释放被占用的资源
foreach (Attachment item in MailMessage_Mai.Attachments)
{
item.Dispose();
}