Attach all files in a folder to an email - vb.net

I am trying to make a ConsoleApplication attach all files in a folder to an email and send it. I know how to do it with a single attachment, but for the life of me, I cannot figure out how to attach all items in a folder.
Current code:
Sub Main()
Try
Dim mail As New MailMessage("from", "to")
Dim client As New SmtpClient()
client.Port = 25
client.DeliveryMethod = SmtpDeliveryMethod.Network
client.UseDefaultCredentials = False
client.Host = ""
mail.Subject = "" + DateTime.Now.AddDays(-1).ToShortDateString()
mail.IsBodyHtml = True
mail.Body = "Test"
Dim file As System.Net.Mail.Attachment
file = New System.Net.Mail.Attachment("Path to single file")
mail.Attachments.Add(file)
client.Send(mail)
Return
Catch [error] As Exception
MsgBox("error")
Return
End Try
End Sub
Thanks in advance
EDIT:
I tried the below code that I found on another post, but it just errors out (and using the ConsoleApplication, I am not sure how to view the exact error its giving)
For Each filePath As String In Directory.GetFiles(My.Settings.FileLoc1)
Dim Attach As New Net.Mail.Attachment(filePath)
mail.Attachments.Add(Attach)
Next

I got it working!
Sub Main()
Try
Dim mail As New MailMessage("from", "too")
Dim client As New SmtpClient()
client.Port = 25
client.DeliveryMethod = SmtpDeliveryMethod.Network
client.UseDefaultCredentials = False
client.Host = ""
mail.Subject = "" + DateTime.Now.AddDays(-1).ToShortDateString()
mail.IsBodyHtml = True
mail.Body = "Test"
For Each filePath As String In Directory.GetFiles(My.Settings.FileLoc1)
Dim Attach As New Net.Mail.Attachment(filePath)
mail.Attachments.Add(Attach)
Next
client.Send(mail)
Return
Catch [error] As Exception
MsgBox("error")
Return
End Try
End Sub

Related

Cant attached printed pdf document as email attachment in VB.net

I am able to create a pdf document and I can browse the folder and open the document with no issue. But when my code try to attach the file as an attachment then it fails with this error, but the path and filename is correct. I suspect the file is somehow open which prevents the attachment.
Proof of files:
Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll
Could not find file 'C:\TEMP\1104280343081_INV0950.pdf'.
This part works perfectly
Dim txtVarFile As String
Dim txtVarEmail As String = "test#test.com"
Dim txtVarPasss As String = "password"
Dim txtVarSMTP As String = "smtp.gmail.com"
Dim intVarPort As Integer = 587
Dim txtVarDescription As String
'Create Invoice and Save as pdf document
txtVarFile = "C:\TEMP\" & strClientNum & "_" & strInvNum & ".pdf"
PageSetupDialog1.Document = PrintDocument1
PageSetupDialog1.PrinterSettings.DefaultPageSettings.Landscape = True
prtFrmInvoice.PrinterSettings = PageSetupDialog1.PrinterSettings
If prtFrmInvoice.PrinterSettings.IsValid Then
prtFrmInvoice.PrinterSettings.PrinterName = "Microsoft Print to PDF"
prtFrmInvoice.PrintFileName = txtVarFile
prtFrmInvoice.PrintAction = Printing.PrintAction.PrintToFile
prtFrmInvoice.Print()
End If
But this does not work, it tells me the file can not be found, but the file is there
Exception is thrown at this line: eMail.From = New MailAddress(txtVarEmail)
'Send copy of Invoice per Email
Try
Dim SmtpServer As New SmtpClient()
Dim eMail As New MailMessage()
'Dim attachment As System.Net.Mail.Attachment
LogFile.Refresh()
SmtpServer.UseDefaultCredentials = False
SmtpServer.Credentials = New Net.NetworkCredential(txtVarEmail, txtVarPasss)
SmtpServer.Port = intVarPort
SmtpServer.EnableSsl = True
SmtpServer.Host = txtVarSMTP
eMail = New MailMessage()
eMail.From = New MailAddress(txtVarEmail)
eMail.To.Add(strClientEmail)
eMail.Subject = "AltHealth Invoice"
eMail.Body = "Please find your latest invoice attached"
'attachment = New System.Net.Mail.Attachment(txtVarFile)
'eMail.Attachments.Add(attachment)
eMail.Attachments.Add(New Attachment(txtVarFile))
SmtpServer.Send(eMail)
MsgBox("The Invoice has been sent sucessfully via email - File: " & txtVarFile)
Catch ex As Exception
MsgBox("Send failure: " & ex.ToString())
End Try

VB.net Crystal report export to html and send as html mail body using outlook

I am trying to send contents of a crystal report as email body using outlook application.
Here is my code in VB.net
Imports outlook = Microsoft.Office.Interop.Outlook
Dim a As String = something.ConnectionString
Dim cryRpt As ReportDocument
Dim username As String = a.Split("=")(3).Split(";")(0) 'get username
Dim password As String = a.Split("=")(4).Split(";")(0) 'get password
cryRpt = New ReportDocument()
Dim Path As String = Application.StartupPath
Dim svPath As String = Application.StartupPath & "\PDF"
If Not Directory.Exists(svPath) Then
Directory.CreateDirectory(svPath)
End If
cryRpt.Load(Path & "\Reports\dr.rpt")
CrystalReportViewer1.ReportSource = cryRpt
cryRpt.SetDatabaseLogon(username, password)
CrystalReportViewer1.Refresh()
Dim myExportOptions As ExportOptions
myExportOptions = cryRpt.ExportOptions
myExportOptions.ExportDestinationType = ExportDestinationType.DiskFile
myExportOptions.ExportFormatType = ExportFormatType.HTML40 'i tried HTML32 also
Dim html40FormatOptions As HTMLFormatOptions = New HTMLFormatOptions()
html40FormatOptions.HTMLBaseFolderName = svPath
html40FormatOptions.HTMLFileName = "dr.htm"
html40FormatOptions.HTMLEnableSeparatedPages = False
html40FormatOptions.HTMLHasPageNavigator = False
html40FormatOptions.UsePageRange = False
myExportOptions.FormatOptions = html40FormatOptions
cryRpt.Export()
Try
Dim oApp As outlook.Application
oApp = New outlook.Application
Dim oMsg As outlook.MailItem
oMsg = oApp.CreateItem(outlook.OlItemType.olMailItem)
oMsg.Subject = txtSubject.Text
oMsg.BodyFormat = outlook.OlBodyFormat.olFormatHTML
oMsg.HTMLBody = ""
oMsg.HTMLBody = getFileAsString(svPath & "\PoPrt\QuotPrt.html")
oMsg.To = txtEmailId.Text
Dim ccArray As New List(Of String)({txtCC1.Text, txtCC2.Text, txtCC3.Text})
Dim cclis As String = String.Join(",", ccArray.Where(Function(ss) Not String.IsNullOrEmpty(ss)))
oMsg.CC = cclis
oMsg.Display(True)
Catch ex As Exception
MsgBox("Something went wrong", vbExclamation)
End Try
SvFormPanel3.Visible = False
the function
Private Function getFileAsString(ByVal file As String) As String
Dim reader As System.IO.FileStream
Try
reader = New System.IO.FileStream(file, IO.FileMode.Open)
Catch e As Exception
MsgBox("Something went wrong. " + e.Message, vbInformation)
End Try
Dim resultString As String = ""
Dim b(1024) As Byte
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Do While reader.Read(b, 0, b.Length) > 0
resultString = resultString & temp.GetString(b)
Array.Clear(b, 0, b.Length)
Loop
reader.Close()
Return resultString
End Function
The report will get exported to the specified location as html. And when we manually open that html file it displays perfectly with border lines and all.
But when its getting added as html body of outlook application, the formatting will be gone, and looks scattered.
can anyone help
Did you try this?
Open outlook, go to, File>Options>Mail
go to section MessageFormat and untick "Reduce message size by removing format..."
I have solved the issue by exporting it into PDF and then convert to Image and embed in email body.

The SMTP server requires a secure connection VB.NET

Dim smtp As New SmtpClient
Dim mail As New MailMessage
smtp.Credentials = New Net.NetworkCredential("mail#gmail", "password")
mail.From = New MailAddress("mail#gmail.com")
mail.To.Add(totxt.Text$)
mail.Body = bodytxt.Text
If Not ListBox1.Items.Count <= 0 Then
Dim d As Integer
Dim attach As New Attachment(ListBox1.Items(d))
mail.Attachments.Add(attach)
End If
mail.Subject = subjecttxt.Text
smtp.EnableSsl = True
smtp.Port = "587"
smtp.Host = "smtp.gmail.com"
smtp.Send(mail)
smtp.Dispose()
done.Text = "Mail sent"
PictureBox4.BackgroundImage = My.Resources.tickfnl
dtls.Visible = False
I am trying to send email from my gmail account.But i am getting the error "The SMTP Server requires a secure connection".I even enabled LESS-SECURE APP login in my account settings.The password and email address is correct.I tried another email but same issue.Any fix ?
I TRIED ALL THE SOLUTIONS FROM THE DUPLICATE LINK,STILL THE SAME PROBLEM
**IF I REMOVE THIS LINE
smtl.enablessl=true
then i get this error
the server resposnse was 5.7.0 **
Fixed the error using EASendMail
Fixed it using EASendmail :
Panel6.Visible = True
done.Text = "Sending..."
''''''''''''''''''''''''
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New EASendMail.SmtpClient()
oMail.From = fromtxt.Text
oMail.To = New AddressCollection(totxt.Text)
oMail.Subject = subjecttxt.Text
If html.CheckAlign = True Then
oMail.HtmlBody = bodytxt.Text
Else
oMail.TextBody = bodytxt.Text
End If
Dim oServer As New SmtpServer(MailConfig.host.Text)
oServer.Port = MailConfig.port.Text
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
oServer.User = fromtxt.Text
oServer.Password = MailConfig.password.Text
Dim r As Integer
If ListBox1.Items.Count <= 0 Then
Else
oMail.AddAttachment(ListBox1.Items(r))
End If
oSmtp.LogFileName = Application.StartupPath & "\maillog.log"
Try
oSmtp.SendMail(oServer, oMail)
done.Text = "Mail sent !"
PictureBox4.BackgroundImage = My.Resources.tickfnl
Catch ex As Exception
aa = MsgBox(ex.Message)
done.Text = "Sending failed."
PictureBox4.BackgroundImage = My.Resources.excll
End Try

send data grid view data in an e-mail using vb.net

i'm trying to send a datagridview (or just the data in the grid) to an e-mail but i only receive a blank e-mail when it's sent, anyone got any ideas how to fix it?
The code im using is this:
Try
SMTP.UseDefaultCredentials = False
SMTP.Credentials = New Net.NetworkCredential("[e-mail address im sending from]", "[password for that e-mail]")
SMTP.Port = 25
SMTP.EnableSsl = True
mail = New MailMessage
mail.From = New MailAddress("[e-mail im sending from]")
mail.To.Add(UserEmail.Text)
mail.Body = DataTab.ToString
mail.Subject = "Biology quiz Highscores"
SMTP.DeliveryMethod = SmtpDeliveryMethod.Network
SMTP.Send(mail)
MsgBox("E-mail sent to: " & UserEmail.Text & "")
Catch ex As Exception
MsgBox("Unable to send e-mail. Please try again later.")
End Try
im getting the data from a 2003 access database using mydataadpter sql statement, the data table variable is called datatab.
Object.ToString(), unless overridden, is identical to calling Object.GetType().ToString().
You want to show the data in the data table. You could do something like this:
Private Sub YourSubWhereYouSendEmail()
'...
Try
Using smtp = New SmtpClient() With {
.UseDefaultCredentials = False,
.Credentials = New Net.NetworkCredential("[e-mail address im sending from]", "[password for that e-mail]"),
.Port = 25,
.EnableSsl = True,
.DeliveryMethod = SmtpDeliveryMethod.Network
}
smtp.Send(New MailMessage("[e-mail im sending from]"), UserEmail.Text, "Biology quiz Highscores", DataTableToCSVString(DataTab)))
End Using
MsgBox("E-mail sent to: " & UserEmail.Text & "")
Catch ex As Exception
MsgBox("Unable to send e-mail. Please try again later.")
End Try
'...
End Sub
Private Function DataTableToCSVString(table As DataTable) As String
With New Text.StringBuilder
Dim once = False
'headers
For Each col As DataColumn In table.Columns
If once = False Then
once = True
Else
.Append(",")
End If
.Append(col.ColumnName)
Next
.AppendLine()
'rows
For Each s In table.Select.Select(Function(row) String.Join(",", row.ItemArray))
.AppendLine(s)
Next
Return .ToString
End With
End Function

What is the usual way to check if internet connection exists and if SMTP mail is sent?

I'm sending emails through VB.NET like in showed code:
Dim retval As Integer
Dim attachment As System.Net.Mail.Attachment = Nothing
If fileName <> "" Then
attachment = New System.Net.Mail.Attachment(fileName)
End If
Dim client As New SmtpClient()
With client
.EnableSsl = True
.Host = smtpServerAddress
.Port = 587
.DeliveryMethod = SmtpDeliveryMethod.Network
.UseDefaultCredentials = False
.Credentials = New NetworkCredential(FromEmailId, password)
AddHandler .SendCompleted, AddressOf SendCompletedCallback
End With
Dim mail = New MailMessage(FromEmailId, toEmailId)
With mail
.Priority = MailPriority.High
.Subject = subject
.SubjectEncoding = System.Text.Encoding.UTF8
.IsBodyHtml = False
If fileName <> "" Then
.Attachments.Add(attachment)
End If
.Body = msgBody
.BodyEncoding = System.Text.Encoding.UTF8
End With
Try
client.SendAsync(mail, "")
retval = 1
Catch ex As Exception
retval = 0
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
Return retval
This work's well.
Problem is only that my Try/Catch block dont react as expected if I'm not connected to internet. The only way I can know that mail didn't go out is that I don't receive message from callback what can take a long time. Also, I get returned 1 from function like email is sended properly.
Which is usual way to check if internet connection exists and if mail is start to be sended?
If you want to catch all exception thrown from SmtpClient you could send mail synchronously. If you prefer asynchronous way, use SendMailAsync which returns Task instance on which you can call ContinueWith to set error handler:
client.SendMailAsync(mail).ContinueWith(t=>HandleError(t.Exception), TaskContinuationOptions.OnlyOnFaulted)