C#使用GMAIL羣髮帶附件郵件的例子

 

說明:

 

做一個要羣發郵件的Excel表,包含:

 

ID,

姓名,

郵箱

 

三列,多個郵箱間用“;”間隔開。

 

對於不同附件的文件名必須包含ID。 

[c-sharp:nogutter] view plaincopy
  1. using System;  
  2. using System.Data;  
  3. using System.Windows.Forms;  
  4. using System.Data.OleDb;  
  5. using System.Net.Mail;  
  6. using System.Net;  
  7. using System.IO;  
  8. namespace Ferry  
  9. {  
  10.     public partial class MassSendMail : Form  
  11.     {  
  12.         public MassSendMail()  
  13.         {  
  14.             InitializeComponent();  
  15.         }  
  16.         private void MassSendMail_Load(object sender, EventArgs e)  
  17.         {  
  18.         }  
  19.         /// <summary>  
  20.         /// 統一的附件  
  21.         /// </summary>  
  22.         private void btnSameAttach_Click(object sender, EventArgs e)  
  23.         {  
  24.             OpenFileDialog ofd = new OpenFileDialog();  
  25.             ofd.Filter = "所有文件|*.*";  
  26.             ofd.ShowDialog();  
  27.             txtSameAttach.Text = ofd.FileName;  
  28.         }  
  29.         /// <summary>  
  30.         /// 不同的附件,必須放在相同目錄  
  31.         /// </summary>  
  32.         private void btnDiffAttach_Click(object sender, EventArgs e)  
  33.         {  
  34.             FolderBrowserDialog fbd = new FolderBrowserDialog();  
  35.             fbd.ShowDialog();  
  36.             txtDiffAttach.Text = fbd.SelectedPath;  
  37.         }  
  38.         private void btnMassSendList_Click(object sender, EventArgs e)  
  39.         {  
  40.             OpenFileDialog ofd = new OpenFileDialog();  
  41.             ofd.Filter = "Excel文件(*.xlsx;*.xls)|*.xlsx;*.xls";  
  42.             ofd.ShowDialog();  
  43.             txtMassSendList.Text = ofd.FileName;  
  44.         }  
  45.         private void MassSendMail_FormClosing(object sender, FormClosingEventArgs e)  
  46.         {  
  47.             if (MessageBox.Show("確定要退出嗎?退出將丟失窗口中所有信息!""警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)  
  48.                 == DialogResult.No)  
  49.             {  
  50.                 e.Cancel = true;  
  51.             }  
  52.         }  
  53.         private void btnQuit_Click(object sender, EventArgs e)  
  54.         {  
  55.             this.Close();  
  56.         }  
  57.         private void btnSend_Click(object sender, EventArgs e)  
  58.         {  
  59.             SendMail();  
  60.         }  
  61.         private void SendMail()  
  62.         {  
  63.             this.btnSend.Enabled = false;  
  64.             #region 讀取設置的信息  
  65.             //郵件主題  
  66.             String strMailSubject = txtMailSubject.Text.Trim();  
  67.             //郵件內容  
  68.             String strMailBody = txtMailBody.Text.Trim();  
  69.             //統一附件文件目錄  
  70.             String strSameFilePath = txtSameAttach.Text.Trim();  
  71.             //不同附件目錄  
  72.             String strDiffFoderPath = txtDiffAttach.Text.Trim();  
  73.             //羣發列表文件路徑  
  74.             String strMassSendList = txtMassSendList.Text.Trim();  
  75.             //郵箱  
  76.             String strMail = txtYourMail.Text.Trim();  
  77.             //郵箱密碼  
  78.             String strPassword = txtYourMailPassword.Text.Trim();  
  79.             //顯示姓名  
  80.             String strDisplayName = txtDisplayName.Text.Trim();  
  81.             #endregion  
  82.             #region 驗證必填信息  
  83.             if (strMailSubject.Length == 0)  
  84.             {  
  85.                 MessageBox.Show("請輸入郵件主題!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  86.                 this.btnSend.Enabled = true;  
  87.                 return;  
  88.             }  
  89.             if (strMailBody.Length == 0)  
  90.             {  
  91.                 MessageBox.Show("請輸入郵件內容!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  92.                 this.btnSend.Enabled = true;  
  93.                 return;  
  94.             }  
  95.             if (strMassSendList.Length == 0)  
  96.             {  
  97.                 MessageBox.Show("請選擇羣發郵件列表Excel文件!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  98.                 this.btnSend.Enabled = true;  
  99.                 return;  
  100.             }  
  101.             if (strMail.Length == 0)  
  102.             {  
  103.                 MessageBox.Show("請輸入郵箱!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  104.                 this.btnSend.Enabled = true;  
  105.                 return;  
  106.             }  
  107.             if (strPassword.Length == 0)  
  108.             {  
  109.                 MessageBox.Show("請輸入郵箱密碼!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  110.                 this.btnSend.Enabled = true;  
  111.                 return;  
  112.             }  
  113.             #endregion  
  114.             #region 讀取羣發郵件列表  
  115.             string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;Persist Security Info=False", strMassSendList);  
  116.             OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [MailList$]", connectionString);  
  117.             DataTable dt = new DataTable();  
  118.             try  
  119.             {  
  120.                 da.Fill(dt);  
  121.             }  
  122.             catch (Exception err)  
  123.             {  
  124.                 MessageBox.Show("從Excel中獲取數據失敗:" + err.Message);  
  125.                 return;  
  126.             }  
  127.             DataRow[] emptyRows = dt.Select("ID = '' OR ID IS NULL OR ID = 'ID'");  
  128.             foreach (DataRow row in emptyRows)  
  129.             {  
  130.                 dt.Rows.Remove(row);  
  131.             }  
  132.             dt.AcceptChanges();  
  133.             dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"] };  
  134.             #endregion  
  135.             foreach (DataRow dr in dt.Rows)  
  136.             {  
  137.                 MailMessage mess = new MailMessage();  
  138.                 if (strDisplayName.Length != 0)  
  139.                 {  
  140.                     mess.From = new MailAddress(strDisplayName + "<" + strMail + ">");  
  141.                 }  
  142.                 else  
  143.                 {  
  144.                     mess.From = new MailAddress(strMail);  
  145.                 }  
  146.                 #region 設置郵件  
  147.                 mess.Subject = strMailSubject.Replace("{Name}", dr["姓名"].ToString());  
  148.                 mess.Body = strMailBody.Replace("{Name}", dr["姓名"].ToString());  
  149.                 mess.IsBodyHtml = true;  
  150.                 String[] strMailAddr = dr["郵箱"].ToString().Trim().Split(';');  
  151.                 for (Int32 i = 0; i < strMailAddr.Length; i++)  
  152.                 {  
  153.                     if (strMailAddr[i].Trim().Length != 0)  
  154.                     {  
  155.                         mess.To.Add(strMailAddr[i]);  
  156.                     }  
  157.                 }  
  158.                 #endregion  
  159.                 #region 添加附件  
  160.                 if (strSameFilePath.Length != 0)  
  161.                 {  
  162.                     mess.Attachments.Add(new Attachment(strSameFilePath));  
  163.                 }  
  164.                 if (strDiffFoderPath.Length != 0)  
  165.                 {  
  166.                     String[] files = Directory.GetFiles(strDiffFoderPath);  
  167.                     for (Int32 j = 0; j < files.Length; j++)  
  168.                     {  
  169.                         if (files[j].ToUpper().Trim().IndexOf(dr["ID"].ToString().Trim().ToUpper()) > 0)  
  170.                         {  
  171.                             mess.Attachments.Add(new Attachment(files[j]));  
  172.                         }  
  173.                     }  
  174.                 }  
  175.                 #endregion  
  176.                 #region  
  177.                 SmtpClient sc = new SmtpClient();  
  178.                 sc.Host = "smtp.gmail.com";  
  179.                 sc.Port = 587;  
  180.                 sc.Credentials = new NetworkCredential(strMail + "@gmail.com", strPassword);  
  181.                 sc.DeliveryMethod = SmtpDeliveryMethod.Network;  
  182.                 sc.EnableSsl = true;  
  183.                 try  
  184.                 {  
  185.                     sc.Send(mess);  
  186.                     this.txtSendMessage.Text += dr["姓名"].ToString() + "......成功/r/n";  
  187.                 }  
  188.                 catch  
  189.                 {  
  190.                     this.txtSendMessage.Text += dr["姓名"].ToString() + "......失敗/r/n";  
  191.                 }  
  192.                 #endregion  
  193.             }  
  194.             this.btnSend.Enabled = true;  
  195.             MessageBox.Show("郵件羣發已完成!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  196.         }  
  197.         private void menuQuit_Click(object sender, EventArgs e)  
  198.         {  
  199.             this.Close();  
  200.         }  
  201.         private void menuSaveMessage_Click(object sender, EventArgs e)  
  202.         {  
  203.             SaveFileDialog sfd = new SaveFileDialog();  
  204.             sfd.Filter = "文本文件(*.txt)|*.txt";  
  205.             DialogResult r = sfd.ShowDialog();  
  206.             String filePath = sfd.FileName.Trim();  
  207.             if (r != DialogResult.Cancel)  
  208.             {  
  209.                 FileStream fs;  
  210.                 if (File.Exists(filePath))  
  211.                 {  
  212.                     fs = File.Open(filePath, FileMode.Append);  
  213.                 }  
  214.                 else  
  215.                 {  
  216.                     fs = File.Open(filePath, FileMode.Create);  
  217.                 }  
  218.                 StreamWriter sw = new StreamWriter(fs);  
  219.                 sw.Write(this.txtSendMessage.Text);  
  220.                 sw.Close();  
  221.                 fs.Close();  
  222.                 GC.Collect();  
  223.                 MessageBox.Show("發送記錄已保存!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  224.             }  
  225.         }  
  226.         private void menuHelp_Click(object sender, EventArgs e)  
  227.         {  
  228.             System.Diagnostics.Process.Start("郵件羣發工具使用說明.docx");  
  229.         }  
  230.         private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)  
  231.         {  
  232.             if (this.WindowState != FormWindowState.Minimized)  
  233.             {  
  234.                 this.WindowState = FormWindowState.Minimized;  
  235.                 this.ShowInTaskbar = false;  
  236.             }  
  237.             else  
  238.             {  
  239.                 this.WindowState = FormWindowState.Normal;  
  240.                 this.ShowInTaskbar = true;  
  241.             }  
  242.         }  
  243.         private void contextMenuQuit_Click(object sender, EventArgs e)  
  244.         {  
  245.             this.Close();  
  246.         }  
  247.     }  
  248. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章