惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
Google Developers Blog
J
Java Code Geeks
爱范儿
爱范儿
Microsoft Azure Blog
Microsoft Azure Blog
美团技术团队
人人都是产品经理
人人都是产品经理
Martin Fowler
Martin Fowler
IT之家
IT之家
博客园_首页
B
Blog RSS Feed
Google DeepMind News
Google DeepMind News
B
Blog
U
Unit 42
Apple Machine Learning Research
Apple Machine Learning Research
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
罗磊的独立博客
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
博客园 - 聂微东
腾讯CDC
A
About on SuperTechFans

博客园 - Ferry

ASP.NET网站权限设计实现(三)——套用JQuery EasyUI列表显示数据、分页、查询 ASP.NET网站权限设计实现(二)——角色权限绑定 ASP.NET读取网络图片并在页面上显示 ASP.NET网站权限设计实现(一)——使用PowerDesigner进行数据库设计 Visual Studio 2010 架构图之用例图(UML Use Case Diagram) ASP.NET MVC3 新的视图引擎(View Engine) 一个德国人图解中西文化差异(值得一看) 微软AJAX CDN(内容分发网络) 注册使用GAC—Global Assembly Cache(.NET) ASP.NET 递归将分类绑定到 TreeView - Ferry 新浪微博PC客户端(DotNet WinForm版)——功能实现分解介绍 新浪微博PC客户端(DotNet WinForm版)—— 初探 C#:30行数据插入到数据库中的效率测试-一行行执行、构造SQL一次执行、SqlBulkCopy ASP.NET Web 应用开发实战快速上手系列 3—C#面向对象编程纲要-类 ASP.NET带进度条多文件上传 ASP.NET4.0中客户端ID的生成 在高优先级下运行应用程序 学习使用NHibernate2.1.0Beta1(续七)— 单例模式 ASP.NET Web 应用开发实战快速上手系列 2——C#基础
C#使用GMAIL群发带附件邮件的例子
Ferry · 2010-11-11 · via 博客园 - Ferry


说明:

做一个要群发邮件的Excel表,包含:

ID,

姓名,

邮箱

三列,多个邮箱间用“;”间隔开。

对于不同附件的文件名必须包含ID。 

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net.Mail;
using System.Net;
using System.IO;namespace Ferry
{
    
public partial class MassSendMail : Form
    {
        
public MassSendMail()
        {
            InitializeComponent();
        }
        
private void MassSendMail_Load(object sender, EventArgs e)
        {

        }

/// <summary>
        
/// 统一的附件
        
/// </summary>
        private void btnSameAttach_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd 
= new OpenFileDialog();
            ofd.Filter 
= "所有文件|*.*";
            ofd.ShowDialog();
            txtSameAttach.Text 
= ofd.FileName;
        }
        
/// <summary>
        
/// 不同的附件,需要指定不同附件所在的统一目录
        
/// </summary>
        private void btnDiffAttach_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd 
= new FolderBrowserDialog();
            fbd.ShowDialog();
            txtDiffAttach.Text 
= fbd.SelectedPath;
        }
private void btnMassSendList_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd 
= new OpenFileDialog();
            ofd.Filter 
= "Excel文件(*.xlsx;*.xls)|*.xlsx;*.xls";
            ofd.ShowDialog();
            txtMassSendList.Text 
= ofd.FileName;
        }
private void MassSendMail_FormClosing(object sender, FormClosingEventArgs e)
        {
            
if (MessageBox.Show("确定要退出吗?退出将丢失窗口中所有信息!""警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                
== DialogResult.No)
            {
                e.Cancel 
= true;
            }
        }
private void btnQuit_Click(object sender, EventArgs e)
        {
            
this.Close();
        }
private void btnSend_Click(object sender, EventArgs e)
        {
            SendMail();
        }
private void SendMail()
        {
            
this.btnSend.Enabled = false;#region 读取设置的信息
            
//邮件主题
            String strMailSubject = txtMailSubject.Text.Trim();
            
//邮件内容
            String strMailBody = txtMailBody.Text.Trim();
            
//统一附件文件目录
            String strSameFilePath = txtSameAttach.Text.Trim();
            
//不同附件目录
            String strDiffFoderPath = txtDiffAttach.Text.Trim();
            
//群发列表文件路径
            String strMassSendList = txtMassSendList.Text.Trim();
            
//邮箱
            String strMail = txtYourMail.Text.Trim();
            
//邮箱密码
            String strPassword = txtYourMailPassword.Text.Trim();
            
//显示姓名
            String strDisplayName = txtDisplayName.Text.Trim();
            
#endregion#region 验证必填信息
            
if (strMailSubject.Length == 0)
            {
                MessageBox.Show(
"请输入邮件主题!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
this.btnSend.Enabled = true;
                
return;
            }
            
if (strMailBody.Length == 0)
            {
                MessageBox.Show(
"请输入邮件内容!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
this.btnSend.Enabled = true;
                
return;
            }
            
if (strMassSendList.Length == 0)
            {
                MessageBox.Show(
"请选择群发邮件列表Excel文件!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
this.btnSend.Enabled = true;
                
return;
            }
            
if (strMail.Length == 0)
            {
                MessageBox.Show(
"请输入邮箱!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
this.btnSend.Enabled = true;
                
return;
            }
            
if (strPassword.Length == 0)
            {
                MessageBox.Show(
"请输入邮箱密码!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
this.btnSend.Enabled = true;
                
return;
            }
            
#endregion#region 读取群发邮件列表
            
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;Persist Security Info=False", strMassSendList);
            OleDbDataAdapter da 
= new OleDbDataAdapter("SELECT * FROM [MailList$]", connectionString);
            DataTable dt 
= new DataTable();
            
try
            {
                da.Fill(dt);
            }
            
catch (Exception err)
            {
                MessageBox.Show(
"从Excel中获取数据失败:" + err.Message);
                
return;
            }
            DataRow[] emptyRows 
= dt.Select("ID = '' OR ID IS NULL OR ID = 'ID'");
            
foreach (DataRow row in emptyRows)
            {
                dt.Rows.Remove(row);
            }
            dt.AcceptChanges();
            dt.PrimaryKey 
= new DataColumn[] { dt.Columns["ID"] };
            
#endregionforeach (DataRow dr in dt.Rows)
            {
                MailMessage mess 
= new MailMessage();if (strDisplayName.Length != 0)
                {
                    mess.From 
= new MailAddress(strDisplayName + "<" + strMail + ">");
                }
                
else
                {
                    mess.From 
= new MailAddress(strMail);
                }
#region 设置邮件
                mess.Subject 
= strMailSubject.Replace("{Name}", dr["姓名"].ToString());
                mess.Body 
= strMailBody.Replace("{Name}", dr["姓名"].ToString());
                mess.IsBodyHtml 
= true;

                String[] strMailAddr 

= dr["邮箱"].ToString().Trim().Split(';');
                
for (Int32 i = 0; i < strMailAddr.Length; i++)
                {
                    
if (strMailAddr[i].Trim().Length != 0)
                    {
                        mess.To.Add(strMailAddr[i]);
                    }
                }
                
#endregion#region 添加附件
                
if (strSameFilePath.Length != 0)
                {
                    mess.Attachments.Add(
new Attachment(strSameFilePath));
                }
                
if (strDiffFoderPath.Length != 0)
                {
                    String[] files 
= Directory.GetFiles(strDiffFoderPath);
                    
for (Int32 j = 0; j < files.Length; j++)
                    {
                        
if (files[j].ToUpper().Trim().IndexOf(dr["ID"].ToString().Trim().ToUpper()) > 0)
                        {
                            mess.Attachments.Add(
new Attachment(files[j]));
                        }
                    }
                }
                
#endregion#region
                SmtpClient sc 
= new SmtpClient();
                sc.Host 
= "smtp.gmail.com";
                sc.Port 
= 587;
                sc.Credentials 
= new NetworkCredential(strMail + "@gmail.com", strPassword);
                sc.DeliveryMethod 
= SmtpDeliveryMethod.Network;
                sc.EnableSsl 
= true;
                
try
                {
                    sc.Send(mess);
                    
this.txtSendMessage.Text += dr["姓名"].ToString() + "......成功\r\n";
                }
                
catch
                {
                    
this.txtSendMessage.Text += dr["姓名"].ToString() + "......失败\r\n";
                }
                
#endregion
            }
this.btnSend.Enabled = true;
            MessageBox.Show(
"邮件群发已完成!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
private void menuQuit_Click(object sender, EventArgs e)
        {
            
this.Close();
        }
private void menuSaveMessage_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd 
= new SaveFileDialog();
            sfd.Filter 
= "文本文件(*.txt)|*.txt";
            DialogResult r 
= sfd.ShowDialog();
            String filePath 
= sfd.FileName.Trim();
            
if (r != DialogResult.Cancel)
            {
                FileStream fs;
                
if (File.Exists(filePath))
                {
                    fs 
= File.Open(filePath, FileMode.Append);
                }
                
else
                {
                    fs 
= File.Open(filePath, FileMode.Create);
                }
                StreamWriter sw 
= new StreamWriter(fs);
                sw.Write(
this.txtSendMessage.Text);
                sw.Close();
                fs.Close();
                GC.Collect();

                MessageBox.Show(

"发送记录已保存!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
private void menuHelp_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(
"邮件群发工具使用说明.docx");
        }
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            
if (this.WindowState != FormWindowState.Minimized)
            {
                
this.WindowState = FormWindowState.Minimized;
                
this.ShowInTaskbar = false;
            }
            
else
            {
                
this.WindowState = FormWindowState.Normal;
                
this.ShowInTaskbar = true;
            }
        }
private void contextMenuQuit_Click(object sender, EventArgs e)
        {
            
this.Close();
        }
    }
}