Function InvioEmailGmail(ByVal UserNames As String, ByVal Passwords As String, ByVal Mittente As String, ByVal Destinatario As String, ByVal Oggetto As String, ByVal Testo As String, Optional ByVal AggiungiFile As Boolean = Nothing, Optional ByVal PercorsoFile As String = Nothing) As Boolean
InvioEmailGmail = False
'imposta destinatario
Dim sendTo As New MailAddress(Destinatario, "Destinatario")
'imposta mittente
Dim from As MailAddress = New MailAddress(Mittente, "Mittente")
'istanzia l'oggetto MailMessage
Dim message As New MailMessage(from, sendTo)
'campi del messaggio
message.IsBodyHtml = True
message.Subject = Oggetto
message.Body = Testo
'Aggiungere File
If AggiungiFile = True And File.Exists(PercorsoFile) = True Then
Dim file As String = PercorsoFile
' Create the file attachment for this e-mail message.
Dim data As New Attachment(file, MediaTypeNames.Application.Octet)
' Add time stamp information for the file.
Dim disposition As ContentDisposition = data.ContentDisposition
disposition.CreationDate = IO.File.GetCreationTime(file)
disposition.ModificationDate = IO.File.GetLastWriteTime(file)
disposition.ReadDate = IO.File.GetLastAccessTime(file)
' Add the file attachment to this e-mail message.
message.Attachments.Add(data)
End If
'credenziali di accesso
Dim basicAuthenticationInfo As New System.Net.NetworkCredential(UserNames, Passwords)
'imposta connesione con il server GMAIL
Dim SMTPServer As New SmtpClient("smtp.gmail.com")
SMTPServer.UseDefaultCredentials = False
SMTPServer.Port = 587
SMTPServer.Credentials = basicAuthenticationInfo
SMTPServer.EnableSsl = True
'invio della mail
Try
SMTPServer.Send(message)
InvioEmailGmail = True
Catch smtpException As SmtpException
MessageBox.Show([String].Format("SmtpException : {0}", smtpException.Message))
Catch ex As Exception
MessageBox.Show(String.Format("Exception: {0}", ex.Message))
End Try
End Function
Private Sub InviaEmailGmail()
Dim Username, Password, Mittente, Destinatario, Oggetto, Testo As String
Username = "username@gmail.com"
Password = "password"
Mittente = "username@gmail.com"
Destinatario = "destinatario@dominio.it"
Oggetto = "Oggetto : Invio Email SMTP VB.NET"
Testo = "Html <b>PROVA E-MAIL </b> VB.NET"
'Parametri che servono per allegare file
'esito = InvioEmailGmail(Username, Password, Mittente, Destinatario, Oggetto, Testo, True, "c:\error.txt")
'Invio Email senza allegare file
esito = InvioEmailGmail(Username, Password, Mittente, Destinatario, Oggetto, Testo)
If esito <> False Then
MsgBox("Inviata E-Mail Correttamente", vbInformation, "INVIATA E-MAIL GMAIL")
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load