Visual Basic.NET - Envío de correos con cifrado TLS o STARTTLS

 
Vista:
sin imagen de perfil

Envío de correos con cifrado TLS o STARTTLS

Publicado por anonymous (4 intervenciones) el 05/09/2018 01:14:43
Buenas estimados amigos!!. Necesito enviar correos con cifrado TLS o STARTTLS desde una aplicación que estoy desarrollando en visual basic .net 2015. He buscado en Internet y no hay posteos en relación al tema, solo con cifrado SSL.. Este es el código:
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
Imports System.Net
Imports System.Net.Mail
Imports System.Net.Mime
 
Module Correo
    Private correos As New MailMessage
    Private envios As New SmtpClient
 
 Sub enviarCorreo(ByVal emisor As String, ByVal origen As String, ByVal password As String, ByVal mensaje As String, ByVal asunto As String, ByVal destinatario As String, ByVal ruta As String)
        Try
            correos.To.Clear()
            correos.Body = String.Empty
            correos.Subject = String.Empty
            correos.Body = mensaje
            correos.Subject = asunto
            correos.IsBodyHtml = True
            correos.To.Add(Trim(destinatario))
            correos.From = New MailAddress(emisor)
 
 
            If ruta <> String.Empty Then
                Dim separador As Char = ";"
                Dim substrings() As String = ruta.Split(separador)
 
                For Each substring In substrings
                    Dim archivo As Net.Mail.Attachment = New Attachment(substring)
                    correos.Attachments.Add(archivo)
                Next
            End If
 
            'Datos importantes no modificables para tener acceso a las cuentas
            Select Case origen
                Case "gmail.com"
                    envios.Host = "smtp.gmail.com"
                Case "hotmail.com", "outlook.com"
                    envios.Host = "smtp.live.com"
                Case "dominio.com" 'Hospedado en hostinger.com
                    envios.Host = "smtp.hostinger.com"
            End Select
 
            envios.EnableSsl = false
            envios.Port = 587          '587;//465;//587;//25 -- puertos que he probado
            envios.Credentials = New System.Net.NetworkCredential(emisor, password)
            envios.Send(correos)
            MsgBox("El mensaje fue enviado correctamente. ", MsgBoxStyle.Information, "Mensaje")
 
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Mensajeria Carnes Selectas JM", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
 
    End Sub
End Module

envié la consulta a Hostinger y esta fue la respuesta:
smtp - smtp.hostinger.com - Puerto 587 - Cifrado TLS
También puede funcionar el puerto 465 - Cifrado Starttls

Las pruebas con Gmail o Hotmail son positivas

Agradecería mucho cualquier luz de ayuda..
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 25
Ha aumentado su posición en 4 puestos en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

Envío de correos con cifrado TLS o STARTTLS

Publicado por Juan Enrique (14 intervenciones) el 05/09/2018 15:53:13
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
'espero y sea lo que buscas, es lo que utilizo 
 
 
'Imports System.Globalization
Imports System.Data.SqlClient
Imports System.Security.Principal
Imports System.Net.Mail
 
Public Class Servidor
 
#Region "Variables Compartidas"
    'Public Shared NombreServidor As String = "" ' "192.168etc" '"ERP86"
    'Public Shared NomBaseDatos As String = "Checador"
    'Public Shared IDUsuario As String = "root"
    'Public Shared ElPassword As String = "Twinc3pt."
 
    Public Shared NombreServidor As String = "192.168etc" '"ERP86"
    '  Public Shared NomBaseDatos_SQL As String = "PRUEBA"
    Public Shared NomBaseDatos As String = "BASEDEDATOS"
    Public Shared IDUsuario As String = "sa_casi_siempre_default_es_sa"
    Public Shared ElPassword As String = "Contraseña"
 
    Public Shared Conexion As String = "server=" + NombreServidor + ";initial catalog=" + NomBaseDatos + ";User ID=" + IDUsuario + ";password=" + ElPassword + ";"
 
    '  Public Shared Conexion_SQL As String = "data source=" + NombreServidor_SQL + ";initial catalog=" + NomBaseDatos_SQL + ";integrated security=false;persist security info=False;User ID=" + IDUsuario_SQL + "; pwd=" + ElPassword_SQL + "; packet size=4096;"
 
 
    ' Public Shared SqlConexion As New MySqlConnection(Conexion)
    Public Shared SqlConexion As SqlClient.SqlConnection = New SqlClient.SqlConnection(Conexion)
    ' Public Shared SqlConexion As SqlClient.SqlConnection = New SqlClient.SqlConnection(Conexion_SQL)
 
 
    Public Shared SysAdmin As Boolean = False
    Public Shared Usuario As String
    Public Shared EMP_EmployeeID As String
    Public Shared EMP_FirstName As String
    Public Shared EMP_LastName As String
    Public Shared EMP_RecordID As String
    Public Shared EMP_EMailAddress As String
    Public Shared EMP_Puesto As String
    Public Shared EMP_Planta As String
    Public Shared IP As String
 
    Public Shared EMP_encKey As String = "CEGP_Twinc3pt"
 
    Public Shared Ruta_Fotos As String = "\\192.168etc\Recursos Humanos\f"
 
 
#End Region
 
#Region "Variables Solicitud Cheques"
    Public Shared tipo_cheque As String
    Public Shared Planta As String
    Public Shared Caja_chica As String
 
    Public Shared solCheq_empresa As String
    Public Shared solCheq_proveedor As String
    Public Shared solCheq_nombre_proveedor As String
    Public Shared solCheq_por_la_cantidad As Decimal
    Public Shared solCheq_moneda As String
    Public Shared solCheq_cuenta_bancaria1 As String
    Public Shared solCheq_cuenta_bancaria2 As String
    Public Shared solCheq_condiciones_pago As String
 
#Region "Variables Solicitud Cheques Grid Especial"
    Public Shared Campo1 As String
    Public Shared Campo2 As String
    Public Shared Campo3 As String
    Public Shared Campo4 As String
    Public Shared Campo5 As String
    Public Shared Campo6 As String
 
    Public Shared Campo1_1(100) As String
    Public Shared Campo2_2(100) As String
    Public Shared Campo3_3(100) As String
    Public Shared Campo4_4(100) As String
    Public Shared Campo5_5(100) As String
    Public Shared Campo6_6(100) As String
 
    Public Shared Grupo_grid As String
 
    Public Shared Campo_encabezado As String
    Public Shared Campo_encabezado_1(100) As String
#End Region
#End Region
 
#Region "Variables Impersonation"
 
    Public Shared LOGON32_LOGON_INTERACTIVE As Integer = 2
    Public Shared LOGON32_PROVIDER_DEFAULT As Integer = 0
    Public Shared impersonationContext As WindowsImpersonationContext
    'Public Shared Admin_Usuario As String = "administrador"
    'Public Shared Admin_Contraseña As String = "contraseña"
 
    Public Shared Admin_Usuario As String = "usuario"
    Public Shared Admin_Contraseña As String = "contraseña"
    ' Public Shared Folder_Temp As String = "C:\Checador\"
    Public Shared Folder_Temp As String = "C:\Integracion\"
 
 
    Declare Function LogonUserA Lib "advapi32.dll" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Integer
    Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, ByVal ImpersonationLevel As Integer, ByRef DuplicateTokenHandle As IntPtr) As Integer
    Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
    Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long
 
 
 
#End Region
 
 
 
    Public Function AbrirConexion_status_sqlconn_trans(ByVal servidor As String,
                                                   ByVal BD As String,
                                                   ByVal Usuario As String,
                                                   ByVal passwd As String) As Object
        Dim Conexion As String
        Dim SqlConexion As SqlClient.SqlConnection
        Dim status As Boolean = False
        Dim objetos(3) As Object
        Dim transaction As SqlClient.SqlTransaction
        Try
            Conexion = "data source=" & servidor &
                       ";initial catalog=" & BD &
                       ";integrated security=false;persist security info=False;User ID=" & Usuario &
                       "; pwd=" & passwd &
                       "; packet size=4096;"
            SqlConexion = New SqlClient.SqlConnection(Conexion)
            SqlConexion.Open()
            transaction = SqlConexion.BeginTransaction()
            status = True
            objetos(1) = SqlConexion
            objetos(2) = transaction
        Catch ex As Exception
            objetos(3) = ex.Message
        End Try
        objetos(0) = status
        Return objetos
    End Function
    Public Function CerrarConexion(ByVal SqlConexion As SqlClient.SqlConnection) As Boolean
        Dim band As Boolean = False
        Try
            SqlConexion.Close()
            band = True
        Catch ex As Exception
            MsgBox("No se puede cerrar la conexion." & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
        Return band
    End Function
 
 
 
    ''SQL
    Public Shared Function ValidaExisteRegistro(ByVal Notas As String, ByVal campoClave As String, ByVal Tabla As String, ByVal conexion As SqlClient.SqlConnection) As Boolean
 
        'Esta Funcion valida que existen registros referentes a lo buscado, para no mostrar un reporte en blanco
        If Not Notas.Equals("") Then
            If conexion.State = ConnectionState.Closed Then
                conexion.Open()
            End If
 
            Dim MiComando As New SqlClient.SqlCommand("Select " + campoClave + " From " + Tabla + " where " + campoClave + " ='" + Notas + "'", conexion)
            Dim Midatareader As SqlClient.SqlDataReader = MiComando.ExecuteReader()
 
            Try
                If Midatareader.Read Then
                    Return True
                Else
                    Return False
                End If
            Catch e As Exception
                Return False
            Finally
                conexion.Close()
                Midatareader.Close()
                MiComando.Dispose()
            End Try
        Else
            Return False
        End If
 
    End Function
    Public Shared Function EjecutarTransaccion(ByVal ListaSentencias As ArrayList, ByVal SqlConexionFun As SqlClient.SqlConnection) As Boolean
        Dim band As Boolean = False
        If SqlConexionFun.State = ConnectionState.Closed Then
            SqlConexionFun.Open()
        End If
        Dim command As SqlCommand = SqlConexionFun.CreateCommand()
        Dim transaction As SqlTransaction
        Dim strSentencia As Object
        Dim sentencia As String = ""
        transaction = SqlConexionFun.BeginTransaction()
        command.Connection = SqlConexionFun
        command.Transaction = transaction
        Try
            For Each strSentencia In ListaSentencias
                sentencia = strSentencia.ToString()
                command.CommandText = sentencia.ToString()
                command.ExecuteNonQuery()
            Next
            transaction.Commit()
            band = True
        Catch ex As Exception
            'MsgBox("No se puede terminar la transaccion.", MsgBoxStyle.Critical)
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            Try
                transaction.Rollback()
            Catch ex2 As Exception
                MsgBox("No se puede revertir la transaccion.", MsgBoxStyle.Critical)
                'MsgBox(ex2.Message, MsgBoxStyle.Critical)
            End Try
        Finally
            SqlConexionFun.Close()
        End Try
        Return band
    End Function
    Public Shared Function RegresaRegistros(ByVal sQuery As String, ByVal SqlConexionFun As SqlClient.SqlConnection) As DataTable
 
        Dim miDataAdapter As New SqlDataAdapter
        Dim miDataTable As New DataTable
 
        Dim miResultado As New DataTable
 
        If Not sQuery.Equals("") Then
 
            Try
                If SqlConexionFun.State = ConnectionState.Closed Then
                    SqlConexionFun.Open()
                End If
 
                miDataAdapter.SelectCommand = New SqlCommand(sQuery, SqlConexionFun)
                miDataAdapter.SelectCommand.CommandTimeout = 90000
                miDataAdapter.Fill(miDataTable)
 
                miResultado = miDataTable
            Catch ex As Exception
                Try
 
                Catch ex2 As Exception
                    'Error controlado
                    MsgBox(ex2.Message)
                End Try
 
            Finally
                SqlConexionFun.Close()
                miDataAdapter.Dispose()
                miDataTable.Dispose()
            End Try
        End If
 
        Return miResultado
 
    End Function
    'Public Shared Function ValidaAlmacen(ByVal almacen As String, ByVal usuario As String, ByVal conexion As SqlClient.SqlConnection) As Boolean
    '    'Esta Funcion valida que existen registros referentes a lo buscado, para no mostrar un reporte en blanco
    '    If Not almacen.Equals("") Then
    '        If conexion.State = ConnectionState.Closed Then
    '            conexion.Open()
    '        End If
 
    '        Dim MiComando As New SqlClient.SqlCommand("Select almacen From  Temp_Inventario_Movil  where Almacen ='" + almacen + "'and usuario ='" + usuario + "' ", conexion)
    '        Dim Midatareader As SqlClient.SqlDataReader = MiComando.ExecuteReader()
 
    '        Try
    '            If Midatareader.Read Then
    '                Return True
    '            Else
    '                Return False
    '            End If
    '        Catch e As Exception
    '            Return False
    '        Finally
    '            conexion.Close()
    '            Midatareader.Close()
    '            MiComando.Dispose()
    '        End Try
    '    Else
    '        Return False
    '    End If
    'End Function
 
 
    Public Shared Function impersonateValidUser(ByVal userName As String, ByVal domain As String, ByVal password As String) As Boolean
 
        Dim tempWindowsIdentity As WindowsIdentity
        Dim token As IntPtr = IntPtr.Zero
        Dim tokenDuplicate As IntPtr = IntPtr.Zero
        impersonateValidUser = False
 
        If RevertToSelf() Then
            If LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
                If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
                    tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
                    impersonationContext = tempWindowsIdentity.Impersonate()
                    If Not impersonationContext Is Nothing Then
                        impersonateValidUser = True
                    End If
                End If
            End If
        End If
        If Not tokenDuplicate.Equals(IntPtr.Zero) Then
            CloseHandle(tokenDuplicate)
        End If
        If Not token.Equals(IntPtr.Zero) Then
            CloseHandle(token)
        End If
    End Function
 
    Public Sub undoImpersonation()
        impersonationContext.Undo()
    End Sub
 
    Friend Class email
#Region "variables"
        Dim correoHost = "smtp.gmail.com"
 
        'Dim correoHost = "smtp.office365.com"
 
        'Dim correoPuerto = "25"
        'Dim correoUsuario As String = "correoelectronico@gmail.com"
        'Dim correoPassword As String = "contraseña"
 
        Dim correoPuerto = "587"
        Public Shared correoUsuario As String = ""
        Public Shared correoPassword As String = ""
 
        Dim EnableSsl = True
        Dim Correo As New MailMessage
        Dim Cliente As New SmtpClient()
        Dim Subject As String
        Dim Body As String
        Dim Reenvio As New ArrayList
        Dim esHtml As Boolean = True
        Dim Priority As New MailPriority
#End Region
#Region "Métodos"
        Sub New()
            Priority = MailPriority.Normal
            esHtml = True
        End Sub
        Public Sub setSubject(ByVal Subject As String)
            Me.Subject = Subject
        End Sub
        Public Sub setBody(ByVal Body As String)
            Me.Body = Body
        End Sub
        Public Sub setReenvio(ByVal Reenvio As ArrayList)
            Me.Reenvio = Reenvio
        End Sub
        Public Sub setesHTML(ByVal esHTML As Boolean)
            Me.esHtml = esHTML
        End Sub
        'Public Sub setAdjunto(ByVal rutaArchivo As String)
        '    Try
        '        Dim att As New System.Net.Mail.Attachment(rutaArchivo)
        '        Correo.Attachments.Add(att)
        '    Catch ex As Exception
        '        MessageBox.Show("Error al intentar adjuntar el archivo" & vbNewLine & "ErrorMag: " & ex.Message, "GpoPolesa", MessageBoxButtons.OK, MessageBoxIcon.Error)
        '    End Try
        'End Sub
#End Region
#Region "Funciones"
        Public Function getSubject() As String
            Return Subject
        End Function
        Public Function getBody() As String
            Return Body
        End Function
        Public Function getReenvio() As ArrayList
            Return Reenvio
        End Function
        Public Function getCorreo() As MailMessage
            Return Correo
        End Function
 
#End Region
        Public Function EnviarCorreo()
 
            Dim enviado = False
 
                Cliente.EnableSsl = True
                Cliente.Host = correoHost
                Cliente.Port = correoPuerto
                Cliente.UseDefaultCredentials = False
                Cliente.Credentials = New System.Net.NetworkCredential(correoUsuario, correoPassword)
 
                ' Correo.From = New System.Net.Mail.MailAddress(correoUsuario, "blabla" + _Alias + "")
 
                Correo.From = New System.Net.Mail.MailAddress(correoUsuario)
 
            If Correo.Subject Is Nothing Then
                Try
                    Correo.Subject = Subject
                Catch ex As Exception
                    MessageBox.Show(ex.Message.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
 
            End If
            If Correo.Body Is Nothing Then
                Try
                    Correo.Body = Body
                Catch ex As Exception
                    MessageBox.Show(ex.Message.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
 
            End If
            For Each element In Reenvio
                Try
                    Correo.ReplyToList.Add(New MailAddress(element))
                Catch ex As Exception
                    MessageBox.Show(ex.Message.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
 
 
            Next
 
            Correo.IsBodyHtml = esHtml
                Application.DoEvents()
                Cliente.Send(Correo)
                Correo.Dispose()
                enviado = True
                ' Catch ex As Exception
                'MessageBox.Show("Error al intentar enviar el correo." & vbNewLine & "ErrorMsg: " & ex.Message, "Dynámica", MessageBoxButtons.OK, MessageBoxIcon.Error)
                ' End Try
 
                Return enviado
 
        End Function
 
 
    End Class
End Class
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Envío de correos con cifrado TLS o STARTTLS

Publicado por anonymous (4 intervenciones) el 05/09/2018 16:04:00
Estimado amigo, voy a probar y le tendré noticias, de antemano agradezco mucho su aporte..
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Envío de correos con cifrado TLS o STARTTLS

Publicado por anonymous (4 intervenciones) el 06/09/2018 20:40:46
gracias amigo. Las pruebas con cuentas gmail.com fueron positivos, pero con el servidor con el cual estoy tratando (hostinger.com) las pruebas fueron negativas.. de todas formas agradezco su aporte!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Envío de correos con cifrado TLS o STARTTLS

Publicado por anonymous (4 intervenciones) el 07/09/2018 22:59:56
Gracias estimado, voy a revisar.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar