說明:
做一個要羣發郵件的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"] };
- #endregion
- foreach (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();
- }
- }
- }