今天谈一下C#(WinForm)如何发送带附件的电子邮件!废话少说,先截图伺候:
首先C#发送邮件需要smtp服务的支持,我也不知道是不是C#只支持smtp协议,不过好像在MSDN里,Mail这个命名空间下只有介绍smtp的方法的,好像没看到POP的,算了,先不要说这个
我们暂时用smtp协议来做就好了!因此首先你要确保你的发件邮箱支持smtp服务,据我说知,雅虎邮箱,HotMail邮箱和GMail邮箱都不支持smtp的,不过没事,还好我们常用的QQ邮箱,163邮箱,新浪邮箱等邮箱都支持smtp的,这样我们就可以用这些邮箱来发邮件了,哈哈,不过QQ邮箱的smtp服务默认是关闭的,需要我们手动去开通,开通很简单,进入你的QQ邮箱后,选择【设置】,在账户选项卡里就有个smtp的复选框,打个勾保存一下就OK了。163邮箱和新浪邮箱开通smtp服务也差不多这样的,很简单。好了 开通好了接下来就开始来讲代码了 OK!
为了方便菜鸟理解,我把整个程序分成一下几部分:
OK 以下代码伺候:
一些全局变量,都有注释的
SmtpClient SmtpClient = null; //设置SMTP协议MailAddress MailAddress_from = null; //设置发信人地址 当然还需要密码MailAddress MailAddress_to = null; //设置收信人地址 不需要密码MailMessage MailMessage_Mai = null;FileStream FileStream_my = null; //附件文件流
1.smtp服务信息设置
#region 设置Smtp服务器信息/// <summary>/// 设置Smtp服务器信息/// </summary>/// <param name="ServerName">SMTP服务名</param>/// <param name="Port">端口号</param>private void setSmtpClient(string ServerHost, int Port){SmtpClient = new SmtpClient();SmtpClient.Host = ServerHost;//指定SMTP服务名 例如QQ邮箱为 smtp.qq.com 新浪cn邮箱为 smtp.sina.cn等SmtpClient.Port = Port; //指定端口号SmtpClient.Timeout = 0; //超时时间}#endregion
2.验证发件人信息
#region 验证发件人信息/// <summary>/// 验证发件人信息/// </summary>/// <param name="MailAddress">发件邮箱地址</param>/// <param name="MailPwd">邮箱密码</param>private void setAddressform(string MailAddress, string MailPwd){//创建服务器认证NetworkCredential NetworkCredential_my = new NetworkCredential(MailAddress, MailPwd);//实例化发件人地址MailAddress_from = new System.Net.Mail.MailAddress(MailAddress, textBoxX4.Text);//指定发件人信息 包括邮箱地址和邮箱密码SmtpClient.Credentials = new System.Net.NetworkCredential(MailAddress_from.Address, MailPwd);;}#endregion
3.添加附件
#region 检测附件大小private bool Attachment_MaiInit(string path){try{FileStream_my = new FileStream(path, FileMode.Open);string name = FileStream_my.Name;int size = (int)(FileStream_my.Length / 1024/1024);FileStream_my.Close();//控制文件大小不大于10Mif (size > 10){MessageBox.Show("文件长度不能大于10M!你选择的文件大小为"+ size.ToString()+"M","警告",MessageBoxButtons.OK,MessageBoxIcon.Warning);return false;}return true;}catch (IOException E){MessageBox.Show(E.Message);return false;}}#endregion
4.正式发送邮件
private void btnSend_Click(object sender, EventArgs e){//检测附件大小 发件必需小于10M 否则返回 不会执行以下代码if (txt_Path.Text != ""){if (!Attachment_MaiInit(txt_Path.Text.Trim())){return;}}if (txt_SmtpServer.Text == ""){MessageBox.Show("请输入SMTP服务器名!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);return;}if (textBoxX2.Text == ""){MessageBox.Show("请输入发件人邮箱地址!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);return;}if (txtformPwd.Text == ""){MessageBox.Show("请输入发件人邮箱密码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);return;}if (dataGridViewX1.Rows.Count == 0){MessageBox.Show("请添加收件人!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);return;}if (MessageBox.Show("您确定要发送当前邮件吗?", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK){try{//初始化Smtp服务器信息setSmtpClient("smtp." + txt_SmtpServer.Text.Trim() + comboBoxEx3.Text, Convert.ToInt32(numericUpDown1.Value));}catch (Exception Ex){MessageBox.Show("邮件发送失败,请确定SMTP服务名是否正确!" + "/n" + "技术信息:/n" + Ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);return;}try{//验证发件邮箱地址和密码setAddressform(textBoxX2.Text.Trim() + comboBoxEx2.Text, txtformPwd.Text.Trim());}catch (Exception Ex){MessageBox.Show("邮件发送失败,请确定发件邮箱地址和密码的正确性!" + "/n" + "技术信息:/n" + Ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);return;}//清空历史发送信息 以防发送时收件人收到的错误信息(收件人列表会不断重复)MailMessage_Mai.To.Clear();//添加收件人邮箱地址foreach (DataGridViewRow row in dataGridViewX1.Rows){MailAddress_to = new MailAddress(row.Cells["Column1"].Value.ToString());MailMessage_Mai.To.Add(MailAddress_to);}MessageBox.Show("收件人:" + dataGridViewX1.Rows.Count.ToString() + " 个");//发件人邮箱MailMessage_Mai.From = MailAddress_from;//邮件主题MailMessage_Mai.Subject = txttitle.Text;MailMessage_Mai.SubjectEncoding = System.Text.Encoding.UTF8;//邮件正文MailMessage_Mai.Body = Rtb_Message.Text;MailMessage_Mai.BodyEncoding = System.Text.Encoding.UTF8;//清空历史附件 以防附件重复发送MailMessage_Mai.Attachments.Clear();//添加附件MailMessage_Mai.Attachments.Add(new Attachment(txt_Path.Text.Trim(), MediaTypeNames.Application.Octet));//注册邮件发送完毕后的处理事件SmtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);//开始发送邮件SmtpClient.SendAsync(MailMessage_Mai, "000000000");}}
5.发送邮件后处理
#region 发送邮件后所处理的函数private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e){try{if (e.Cancelled){MessageBox.Show("发送已取消!");}if (e.Error != null){ MessageBox.Show("邮件发送失败!" + "/n" + "技术信息:/n" + e.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); }else{MessageBox.Show("邮件成功发出!", "恭喜!", MessageBoxButtons.OK, MessageBoxIcon.Information);}}catch (Exception Ex){MessageBox.Show("邮件发送失败!" + "/n" + "技术信息:/n" + Ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);} }#endregion
新闻热点
疑难解答