15 апреля 2014
Кравченко Виктор

Как отправить файл по электронной почте?

VB.NET Полезные функции
01

Многим доводилось сталкиваться с необходимостью программно отправлять электронные письма. Я предлагаю следующее решение этого вопроса. Создадим функцию с параметрами, набор которых, отвечает большинству существующих задач. При необходимости каждый может изменить её под свои нужды. Далее, для удобства пользования, мы напишем несколько перегруженных вариантов.

02 VB.NET
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
Public Function SendEmail(email As String, _ subject As String, _ body As String, _ attachements() As Attachment, _ CC() As MailAddress, _ Bcc() As MailAddress, _ encoding As Encoding) As Boolean Try ' Устанавливаем кодировку, используемую по умолчанию - UTF8. If encoding Is Nothing Then encoding = System.Text.Encoding.UTF8 ' Создаем клиента Dim client As SmtpClient ' Указываем настройки почтового клиента client = New SmtpClient("SMTP/IMAP сервер", 25) client.EnableSsl = False 'True - Если требуется SSL проверка client.UseDefaultCredentials = False ' True - Если требуется Проверка подлинности client.Credentials = New System.Net.NetworkCredential("Логин", "Пароль")
' Указываем отправителя и адресата ' Если при получении сообщения поле Отправитель искажается, необходимо ' заменить 'encoding' на 'System.Text.Encoding.GetEncoding(1251)'
Dim emailFrom As MailAddress = New MailAddress("notify@codius.ru", "Система уведомлений Codius.ru", encoding) ' Создаем сообщение Dim message As MailMessage = New MailMessage() message.From = emailFrom 'Отправитель ' Если в поле КОМУ стоит несколько адресатов, обрабатываем: Dim emailTo() As MailAddress = ПолучитьСписокАдресов(email) 'Дополнительная функция, показана ниже For Each toItem As MailAddress In emailTo message.To.Add(toItem) 'Добавляем каждого получателя Next ' Если нужно, добавляем адресатов в копию For Each ccItem As MailAddress In CC message.CC.Add(ccItem) Next ' Если нужно, добавляем адресатов в скрытую копию For Each bccItem As MailAddress In Bcc message.Bcc.Add(bccItem) Next ' Все должно быть в одной кодировке, чтобы не всплывали баги! message.BodyEncoding = encoding message.HeadersEncoding = encoding message.SubjectEncoding = encoding message.Body = body 'Тело письма message.Subject = subject 'Тема письма ' Если есть вложения - то включаем их в письмо For Each attachement As Attachment In attachements message.Attachments.Add(attachement) Next client.Send(message) Catch ex As Exception MsgBox(ex.ToString) Return False End Try Return True End Function
03

Добавляем вспомогательную функцию по обработке строки с адресами:

04 VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#Region "Вспомогательные функции"
' Вспомогательные функции ''' <summary> ''' Функция позволяет преобразовать строку с адресами в массив адресов ''' </summary> ''' <param name="email">строка со списком адресов, разделенных запятыми или двоеточиями</param> ''' <returns>Возвращает массив адресов - List(Of MailAddress)</returns>
Public Function ПолучитьСписокАдресов(email As String) As MailAddress() Dim addrs As New List(Of MailAddress) email = email.Replace(",", ";") 'Если в качестве разделителя адресов используется запятая For Each mailAddr As String In email.Split(";").Where(Function(m) Not String.IsNullOrWhiteSpace(m)) addrs.Add(New MailAddress(mailAddr.Trim)) Next Return addrs.ToArray End Function
#End Region
05

Дописываем перегруженные варианты:

06 VB.NET
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#Region "Перегруженные функции"
'Public Function SendEmail(email As String, subject As String, body As String) As Boolean 'Public Function SendEmail(email As String, subject As String, body As String, attachements() As String) As Boolean 'Public Function SendEmail(email As String, subject As String, body As String, attachements() As String, encoding As Encoding) As Boolean 'Public Function SendEmail(email As String, subject As String, body As String, attachements() As String, CC As String, Bcc As String, encoding As Encoding) As Boolean 'Public Function SendEmail(email As String, subject As String, body As String, attachements As Attachment) As Boolean 'Public Function SendEmail(email As String, subject As String, body As String, attachements As Attachment, encoding As Encoding) As Boolean 'Public Function SendEmail(email As String, subject As String, body As String, attachements As Attachment, CC As String, Bcc As String, encoding As Encoding) As Boolean 'Public Function SendEmail(email As String, subject As String, body As String, attachements() As Attachment) As Boolean 'Public Function SendEmail(email As String, subject As String, body As String, attachements() As Attachment, encoding As Encoding) As Boolean 'Public Function SendEmail(email As String, subject As String, body As String, attachements() As Attachment, CC As String, Bcc As String, encoding As Encoding) As Boolean
' Перегруженные функции
Public Function SendEmail(email As String, _ subject As String, _ body As String _ ) As Boolean Return SendEmail(email, subject, body, CType({}, Attachment()), "", "", Nothing) End Function
Public Function SendEmail(email As String, _ subject As String, _ body As String, _ attachements() As String) As Boolean Return SendEmail(email, subject, body, attachements) End Function
Public Function SendEmail(email As String, _ subject As String, _ body As String, _ attachements() As String, _ encoding As Encoding) As Boolean Return SendEmail(email, subject, body, attachements, "", "", encoding) End Function
Public Function SendEmail(email As String, _ subject As String, _ body As String, _ attachements() As String, _ CC As String, _ Bcc As String, _ encoding As Encoding) As Boolean Dim attCount As Integer = attachements.Length Dim mCC() As MailAddress = ПолучитьСписокАдресов(CC) Dim mBcc() As MailAddress = ПолучитьСписокАдресов(Bcc) ' Создаем массив вложений из путей к файлам Dim attachementPaths(attCount) As Attachment For i As Integer = 0 To attCount - 1 attachementPaths(i) = New Attachment(attachements(i)) Next Return SendEmail(email, subject, body, attachementPaths, mCC, mBcc, encoding) End Function
Public Function SendEmail(email As String, _ subject As String, _ body As String, _ attachements As Attachment) As Boolean Return SendEmail(email, subject, body, {attachements}, "", "", Nothing) End Function
Public Function SendEmail(email As String, _ subject As String, _ body As String, _ attachements As Attachment, _ encoding As Encoding) As Boolean Return SendEmail(email, subject, body, {attachements}, "", "", encoding) End Function
Public Function SendEmail(email As String, _ subject As String, _ body As String, _ attachements As Attachment, _ CC As String, _ Bcc As String, _ encoding As Encoding) As Boolean Dim mCC() As MailAddress = ПолучитьСписокАдресов(CC) Dim mBcc() As MailAddress = ПолучитьСписокАдресов(Bcc) Return SendEmail(email, subject, body, {attachements}, mCC, mBcc, encoding) End Function
Public Function SendEmail(email As String, _ subject As String, _ body As String, _ attachements() As Attachment) As Boolean Return SendEmail(email, subject, body, attachements, "", "", Nothing) End Function
Public Function SendEmail(email As String, _ subject As String, _ body As String, _ attachements() As Attachment, _ encoding As Encoding) As Boolean Return SendEmail(email, subject, body, attachements, "", "", encoding) End Function
Public Function SendEmail(email As String, _ subject As String, _ body As String, _ attachements() As Attachment, _ CC As String, _ Bcc As String, _ encoding As Encoding) As Boolean Dim mCC() As MailAddress = ПолучитьСписокАдресов(CC) Dim mBcc() As MailAddress = ПолучитьСписокАдресов(Bcc) Return SendEmail(email, subject, body, attachements, mCC, mBcc, Nothing) End Function
#End Region
07

Варианты использования функции:

08 VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
' Вариант 1. Примитивный '===============================================================================
Return SendEmail("СписокПолучателей", "ТемаПисьма", "ТекстПисьма")
' Вариант 2. С вложением '===============================================================================
Return SendEmail("СписокПолучателей", "ТемаПисьма", "ТекстПисьма", {"ПутьКФайлу1", "ПутьКФайлу2"})
' Вариант 3. С переименованием вложенных файлов '===============================================================================
Dim filePath As String = System.AppDomain.CurrentDomain.BaseDirectory + "Downloads\" + realFileName.ToString If IO.File.Exists(filePath) Then ' Проверяем существует ли файл ' Здесь получаем то имя файла, с которым мы хотели бы, чтобы его увидел получатель Dim fileName As String = "НовоеИмяФайла" Try Dim fs As System.IO.FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read) Dim attachement As Attachment = New Attachment(fs, fileName) Return SendEmail(email, "ТемаПисьма", "ТекстПисьма", attachement) Catch ex As Exception Return ex.ToString End Try Return True End If
09

Что почитать:

10

Похожие запросы:

  • how to send an email with attachment in vb.net?
  • VB.NET Email Attachment
  • Sending Email to multiple recipients in VB.NET
  • Sending multiple email with vb.net 2010 problem
  • Send email to multiple recipients
  • VB.Net — sending multiple e-mail addresses vb program
comments powered by HyperComments