前兩天有個朋友讓我幫他找個郵件羣發工具,自己感覺找起來麻煩,就動手幫他寫了一個。該工具使C#編寫,與數據庫相結合實現羣發功能。
界面的設計很簡單,只需在WinForm上拖幾個TextBox控件和一個RichTextBox控件,讓用戶填寫郵件的標題和內容,再添加一個按鈕雙擊後添加如下代碼:
MailMessage message = new MailMessage();
message.Subject = this.textBoxSubject.Text.Trim();
message.From = new MailAddress(this.textBoxFromMail.Text.Trim());
message.Body = this.richTextBoxContent.Text.Trim();
message.IsBodyHtml = true;
string strConnection = "Server=(local);initial catalog=mail;user id=sa;password=sa;Connect Timeout=30";
SqlConnection objConnection=new SqlConnection(strConnection);
try
{
objConnection.Open();
MessageBox.Show("數據庫連接成功!");
}
catch (Exception ee)
{
MessageBox.Show(ee.ToString());
}
SqlCommand sqlCommand = new SqlCommand("Select * from mail", objConnection);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
message.To.Add(reader["address"].ToString());
MessageBox.Show("地址添加成功!");
}
objConnection.Close();
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(message);
MessageBox.Show("郵件發送成功!");
message.Subject = this.textBoxSubject.Text.Trim();
message.From = new MailAddress(this.textBoxFromMail.Text.Trim());
message.Body = this.richTextBoxContent.Text.Trim();
message.IsBodyHtml = true;
string strConnection = "Server=(local);initial catalog=mail;user id=sa;password=sa;Connect Timeout=30";
SqlConnection objConnection=new SqlConnection(strConnection);
try
{
objConnection.Open();
MessageBox.Show("數據庫連接成功!");
}
catch (Exception ee)
{
MessageBox.Show(ee.ToString());
}
SqlCommand sqlCommand = new SqlCommand("Select * from mail", objConnection);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
message.To.Add(reader["address"].ToString());
MessageBox.Show("地址添加成功!");
}
objConnection.Close();
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(message);
MessageBox.Show("郵件發送成功!");
如此之外,還需要在Config文件中添加如下的配置信息:
<configuration>
<system.net>
<mailSettings>
<smtp>
<network host="smtp.163.com" password="" port="25" userName="" defaultCredentials="false"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
<system.net>
<mailSettings>
<smtp>
<network host="smtp.163.com" password="" port="25" userName="" defaultCredentials="false"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
代碼中引入了.NET中的命名空間System.Net.Mail,微軟在這個命名空間下提供了相關的Class來實現郵件發送功能,有興趣的朋友可以到MSDN上查看相關介紹.