今天談一下C#(WinForm)如何發送帶附件的電子郵件!廢話少說,先截圖伺候:
首先C#發送郵件需要smtp服務的支持,我也不知道是不是C#只支持smtp協議,不過好像在MSDN里,Mail這個命名空間下只有介紹smtp的方法的,好像沒看到POP的,算了,先不要說這個
我們暫時用smtp協議來做就好了!因此首先你要確保你的發件郵箱支持smtp服務,據我說知,雅虎郵箱,HotMail郵箱和GMail郵箱都不支持smtp的,不過沒事,還好我們常用的QQ郵箱,163郵箱,新浪郵箱等郵箱都支持smtp的,這樣我們就可以用這些郵箱來發郵件了,哈哈,不過QQ郵箱的smtp服務默認是關閉的,需要我們手動去開通,開通很簡單,進入你的QQ郵箱后,選擇【設置】,在賬戶選項卡里就有個smtp的復選框,打個勾保存一下就OK了。163郵箱和新浪郵箱開通smtp服務也差不多這樣的,很簡單。好了 開通好了接下來就開始來講代碼了 OK!
為了方便菜鳥理解,我把整個程序分成一下幾部分:
- smtp服務信息設置
- 驗證發件人信息
- 添加附件
- 正式發送郵件
- 發送郵件后處理
OK 以下代碼伺候:
一些全局變量,都有注釋的
1
2
3
4
5
|
SmtpClient SmtpClient = null ; //設置SMTP協議 MailAddress MailAddress_from = null ; //設置發信人地址 當然還需要密碼 MailAddress MailAddress_to = null ; //設置收信人地址 不需要密碼 MailMessage MailMessage_Mai = null ; FileStream FileStream_my = null ; //附件文件流 |
1.smtp服務信息設置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#region 設置Smtp服務器信息 /// <summary> /// 設置Smtp服務器信息 /// </summary> /// <param name="ServerName">SMTP服務名</param> /// <param name="Port">端口號</param> private void setSmtpClient( string ServerHost, int Port) { SmtpClient = new SmtpClient(); SmtpClient.Host = ServerHost; //指定SMTP服務名 例如QQ郵箱為 smtp.qq.com 新浪cn郵箱為 smtp.sina.cn等 SmtpClient.Port = Port; //指定端口號 SmtpClient.Timeout = 0; //超時時間 } #endregion |
2.驗證發件人信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#region 驗證發件人信息 /// <summary> /// 驗證發件人信息 /// </summary> /// <param name="MailAddress">發件郵箱地址</param> /// <param name="MailPwd">郵箱密碼</param> private void setAddressform( string MailAddress, string MailPwd) { //創建服務器認證 NetworkCredential NetworkCredential_my = new NetworkCredential(MailAddress, MailPwd); //實例化發件人地址 MailAddress_from = new System.Net.Mail.MailAddress(MailAddress, textBoxX4.Text); //指定發件人信息 包括郵箱地址和郵箱密碼 SmtpClient.Credentials = new System.Net.NetworkCredential(MailAddress_from.Address, MailPwd); ; } #endregion |
3.添加附件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
#region 檢測附件大小 private bool Attachment_MaiInit( string path) { try { FileStream_my = new FileStream(path, FileMode.Open); string name = FileStream_my.Name; int size = ( int )(FileStream_my.Length / 1024/1024); FileStream_my.Close(); //控制文件大小不大于10M if (size > 10) { MessageBox.Show( "文件長度不能大于10M!你選擇的文件大小為" + size.ToString()+ "M" , "警告" ,MessageBoxButtons.OK,MessageBoxIcon.Warning); return false ; } return true ; } catch (IOException E) { MessageBox.Show(E.Message); return false ; } } #endregion |
4.正式發送郵件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
private void btnSend_Click( object sender, EventArgs e) { //檢測附件大小 發件必需小于10M 否則返回 不會執行以下代碼 if (txt_Path.Text != "" ) { if (!Attachment_MaiInit(txt_Path.Text.Trim())) { return ; } } if (txt_SmtpServer.Text == "" ) { MessageBox.Show( "請輸入SMTP服務器名!" , "提示" , MessageBoxButtons.OK, MessageBoxIcon.Warning); return ; } if (textBoxX2.Text == "" ) { MessageBox.Show( "請輸入發件人郵箱地址!" , "提示" , MessageBoxButtons.OK, MessageBoxIcon.Warning); return ; } if (txtformPwd.Text == "" ) { MessageBox.Show( "請輸入發件人郵箱密碼!" , "提示" , MessageBoxButtons.OK, MessageBoxIcon.Warning); return ; } if (dataGridViewX1.Rows.Count == 0) { MessageBox.Show( "請添加收件人!" , "提示" , MessageBoxButtons.OK, MessageBoxIcon.Warning); return ; } if (MessageBox.Show( "您確定要發送當前郵件嗎?" , "詢問" , MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) { try { //初始化Smtp服務器信息 setSmtpClient( "smtp." + txt_SmtpServer.Text.Trim() + comboBoxEx3.Text, Convert.ToInt32(numericUpDown1.Value)); } catch (Exception Ex) { MessageBox.Show( "郵件發送失敗,請確定SMTP服務名是否正確!" + "\n" + "技術信息:\n" + Ex.Message, "錯誤" , MessageBoxButtons.OK, MessageBoxIcon.Error); return ; } try { //驗證發件郵箱地址和密碼 setAddressform(textBoxX2.Text.Trim() + comboBoxEx2.Text, txtformPwd.Text.Trim()); } catch (Exception Ex) { MessageBox.Show( "郵件發送失敗,請確定發件郵箱地址和密碼的正確性!" + "\n" + "技術信息:\n" + Ex.Message, "錯誤" , MessageBoxButtons.OK, MessageBoxIcon.Error); return ; } //清空歷史發送信息 以防發送時收件人收到的錯誤信息(收件人列表會不斷重復) MailMessage_Mai.To.Clear(); //添加收件人郵箱地址 foreach (DataGridViewRow row in dataGridViewX1.Rows) { MailAddress_to = new MailAddress(row.Cells[ "Column1" ].Value.ToString()); MailMessage_Mai.To.Add(MailAddress_to); } MessageBox.Show( "收件人:" + dataGridViewX1.Rows.Count.ToString() + " 個" ); //發件人郵箱 MailMessage_Mai.From = MailAddress_from; //郵件主題 MailMessage_Mai.Subject = txttitle.Text; MailMessage_Mai.SubjectEncoding = System.Text.Encoding.UTF8; //郵件正文 MailMessage_Mai.Body = Rtb_Message.Text; MailMessage_Mai.BodyEncoding = System.Text.Encoding.UTF8; //清空歷史附件 以防附件重復發送 MailMessage_Mai.Attachments.Clear(); //添加附件 MailMessage_Mai.Attachments.Add( new Attachment(txt_Path.Text.Trim(), MediaTypeNames.Application.Octet)); //注冊郵件發送完畢后的處理事件 SmtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); //開始發送郵件 SmtpClient.SendAsync(MailMessage_Mai, "000000000" ); } } |
5.發送郵件后處理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#region 發送郵件后所處理的函數 private static void SendCompletedCallback( object sender, AsyncCompletedEventArgs e) { try { if (e.Cancelled) { MessageBox.Show( "發送已取消!" ); } if (e.Error != null ) { MessageBox.Show( "郵件發送失敗!" + "\n" + "技術信息:\n" + e.ToString(), "錯誤" , MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show( "郵件成功發出!" , "恭喜!" , MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception Ex) { MessageBox.Show( "郵件發送失敗!" + "\n" + "技術信息:\n" + Ex.Message, "錯誤" , MessageBoxButtons.OK, MessageBoxIcon.Error); } } #endregion |