• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#使用GMAIL群发带附件邮件的例子

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 


 

说明:

 

做一个要群发邮件的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();
        }
    }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#分割字符串发布时间:2022-07-13
下一篇:
c#全选和批量修改发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap