以下代碼已通過VS2008測試。
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
''' <summary>
''' 通過SmtpClient類發(fā)送電子郵件
''' </summary>
''' <param name="ReceiveAddressList">收件人地址列表
''' <param name="Subject">郵件主題
''' <param name="Content">郵件內(nèi)容
''' <param name="AttachFile">附件列表Hastable。KEY=文件名,Value文件路徑
''' <returns></returns>
''' <remarks></remarks>
Private Function SendMail(ByVal ReceiveAddressList As List(Of String), ByVal Subject As String, ByVal Content As String, _
Optional ByVal AttachFile As Hashtable = Nothing) As Boolean
Dim i As Integer
'SMTP客戶端
Dim smtp As New System.Net.Mail.SmtpClient("smtp.163.com")
'smtp.Host = "smtp.163.com" 'SMTP服務器名稱
'發(fā)件人郵箱身份驗證憑證。 參數(shù)分別為 發(fā)件郵箱登錄名和密碼
smtp.Credentials = New System.Net.NetworkCredential("郵箱登錄名", "密碼")
'創(chuàng)建郵件
Dim mail As New System.Net.Mail.MailMessage()
'主題編碼
mail.SubjectEncoding = System.Text.Encoding.GetEncoding("GB2312")
'正文編碼
mail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312")
'郵件優(yōu)先級
mail.Priority = System.Net.Mail.MailPriority.Normal
'以HTML格式發(fā)送郵件,為false則發(fā)送純文本郵箱
mail.IsBodyHtml = True
'發(fā)件人郵箱
mail.From = New System.Net.Mail.MailAddress("郵箱地址")
'添加收件人,如果有多個,可以多次添加
If ReceiveAddressList.Count = 0 Then Return False
For i = 0 To ReceiveAddressList.Count - 1
mail.To.Add(ReceiveAddressList.Item(i))
Next
'郵件主題和內(nèi)容
mail.Subject = Subject
mail.Body = Content
'定義附件,參數(shù)為附件文件名,包含路徑,推薦使用絕對路徑
If Not AttachFile Is Nothing AndAlso AttachFile.Count <> 0 Then
For i = 0 To AttachFile.Count - 1
Dim objFile As New System.Net.Mail.Attachment(AttachFile.Values(i))
'附件文件名,用于收件人收到附件時顯示的名稱
objFile.Name = AttachFile.Keys(i)
'加入附件,可以多次添加
mail.Attachments.Add(objFile)
Next
End If
'發(fā)送郵件
Try
smtp.Send(mail)
MessageBox.Show("郵件發(fā)送成功!")
Return True
Catch
MessageBox.Show("郵件發(fā)送失敗!")
Return False
Finally
mail.Dispose()
End Try
End Function