Below is the email code I am using to send an email with attached document, but when I try to delete the files it is showing that the files are in use. Any help will be appreciated.
Sub email()
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Dim body As String
Dim address As String
Dim address2 As String
Dim address3 As String
Dim fileReader As System.IO.StreamReader
fileReader = My.Computer.FileSystem.OpenTextFileReader("C:\VB Test\location.txt")
Dim Pathstore As String
Pathstore = fileReader.ReadLine()
'email address
Dim lines() As String = System.IO.File.ReadAllLines("C:\VB Test\stores.txt")
For Each line As String In Filter(lines, Pathstore)
Dim fields() As String = line.Split(",")
address = fields(4)
address2 = fields(2)
address3 = fields(6)
Next
Dim fileReader2 As System.IO.StreamReader
fileReader2 = My.Computer.FileSystem.OpenTextFileReader("C:\VB Test\rmmsiul.dll")
Dim Pathcode As String
Pathcode = fileReader2.ReadLine()
fileReader2.Close()
body = "Here are the manual reciepts I created today." + vbNewLine + vbNewLine + vbNewLine & "Thank you," + vbNewLine + Pathstore
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("Do-Not-Reply#suncommobile.com", Pathcode)
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.office365.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress("Do-Not-Reply#suncommobile.com")
e_mail.CC.Add(address)
e_mail.CC.Add(address2)
e_mail.CC.Add(address3)
e_mail.Subject = Pathstore + " Manual reciepts"
e_mail.IsBodyHtml = False
e_mail.Body = body
Dim filepath As String
For Each filepath In Directory.GetFiles("C:\VB Test\Receipts")
Dim Attach As New Net.Mail.Attachment(filepath)
e_mail.Attachments.Add(Attach)
Kill(filepath)
Next
Smtp_Server.Send(e_mail)
MsgBox("E-mail Sent.")
Module1.filedelete()
End Sub
'changed part of the code to the following, but getting error when sending email.
For Each filepath As String In Directory.GetFiles("C:\VB Test\Receipts")
Using reader As New StreamReader(filepath)
Dim a As New Net.Mail.Attachment(reader.BaseStream, filepath)
e_mail.Attachments.Add(a)
End Using
Next
Smtp_Server.Send(e_mail)
Public Sub email()
Dim Pathstore As String = String.Empty
Dim Pathcode As String = String.Empty
With New StreamReader("C:\VB Test\location.txt")
Pathstore = .ReadLine()
.Dispose()
End With
' Are you sure this is the correct file ?
With New StreamReader("C:\VB Test\rmmsiul.dll")
Pathcode = .ReadLine()
.Dispose()
End With
' Capture the list of Attachment Files here, then use it twice below
Dim Attachments() As String = Directory.GetFiles("C:\VB Test\Receipts")
Dim e_mail As New Net.Mail.MailMessage()
With e_mail
.From = New Net.Mail.MailAddress("Do-Not-Reply#suncommobile.com")
.Subject = String.Format("{0} Manual reciepts", Pathstore)
.Body = String.Format("Here are the manual reciepts I created today.{0}{0}{0}Thank you,{0}{1}", Environment.NewLine, Pathstore)
' Since I don't know what Filter() returns, this is best guess to reproduce the same outcome
For Each line As String In Filter(File.ReadAllLines("C:\VB Test\stores.txt"), Pathstore)
Dim fields() As String = line.Split(",")
.CC.Clear()
.CC.Add(fields(4))
.CC.Add(fields(2))
.CC.Add(fields(6))
Next
For Each filepath In Attachments
.Attachments.Add(New Net.Mail.Attachment(filepath))
Next
End With
With New Net.Mail.SmtpClient
.Host = "smtp.office365.com"
.Credentials = New Net.NetworkCredential("Do-Not-Reply#suncommobile.com", Pathcode)
.Port = 587
.EnableSsl = True
.Send(e_mail)
End With
' Dispose the MailMessage to release the holds on the Attachment Files
e_mail.Dispose()
' Delete the Attachment Files
For Each filepath In Attachments
File.Delete(filepath)
Next
MsgBox("E-mail Sent.")
End Sub
Related
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.
I am working on a download feature for my GUI that will allow the end user to be able to input a 5 digit job number and download only those files from the FTP site. In doing this, I have been able to get a list of the directory, but I have not been able to use that list to get the files. Any help on the code shown would be appreciated.
Dim UserName As String
' Sets Username to current logged-in user profile
UserName = Environment.UserName
Dim JobNo As String
JobNo = Textbox1.Text
Dim listRequest As FtpWebRequest = WebRequest.Create("ftp://ftp.site.com/INPUT/" & JobNo & "_*.DBF")
listRequest.Credentials = New System.Net.NetworkCredential(“Username”, “Password”)
listRequest.Method = WebRequestMethods.Ftp.ListDirectory
Dim listResponse As FtpWebResponse = listRequest.GetResponse()
Dim reader As StreamReader = New StreamReader(listResponse.GetResponseStream())
For Each foundFile As String In
My.Computer.Network.DownloadFile("ftp://ftp.site.com/INPUT/" & foundFile, "C:\users\” & UserName & “\desktop\temp\" & foundFile, “Username”, “Password”)
Next
Below is the final output that worked. The overall
Dim UserName As String
' Sets Username to current logged-in user profile
UserName = Environment.UserName
Dim JobNo As String
JobNo = Textbox1.Text
'DOWNLOADING FROM THE FTP JOBS PROCESSED FOLDER
Dim listRequest As FtpWebRequest = WebRequest.Create(“ftp.site.com/input/” & JobNo & "_*.DBF")
listRequest.Credentials = New System.Net.NetworkCredential(“Username”, “Password”)
listRequest.Method = WebRequestMethods.Ftp.ListDirectory
Dim listResponse As FtpWebResponse = listRequest.GetResponse()
Dim reader As StreamReader = New System.IO.StreamReader(listResponse.GetResponseStream())
Dim Filedata As String = reader.ReadToEnd
Dim directory() As String = Filedata.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
'CREATES TEAM FILE FOLDERS ON LOCAL COMPUTER
My.Computer.FileSystem.CreateDirectory("C:\users\" & UserName & "\desktop\TEAMFILES\IMB_APPEND\A_TEAM")
My.Computer.FileSystem.CreateDirectory("C:\users\" & UserName & "\desktop\TEAMFILES\IMB_APPEND\B_TEAM")
'CLEAR TEXTBOX2
TextBox2.Clear()
For Each foundFile As String In directory
ATEAMdown(foundFile)
TextBox2.Text = TextBox2.Text & foundFile & vbNewLine
Next
'DOWNLOADING FROM THE IMB FTP XMPIE TEAM FOLDER
listRequest = WebRequest.Create(“ftp.site.com/input/” & JobNo & "_*.DBF")
listRequest.Credentials = New System.Net.NetworkCredential(“Username”, “Password”)
listRequest.Method = WebRequestMethods.Ftp.ListDirectory
listResponse = listRequest.GetResponse()
reader = New System.IO.StreamReader(listResponse.GetResponseStream())
Filedata = reader.ReadToEnd
directory = Filedata.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
For Each foundFile As String In directory
BTEAMdown(foundFile)
TextBox2.Text = TextBox2.Text & foundFile & vbNewLine
Next
I was trying to download files from the FTP based on the list that was created using ListDirectory, but it was not split in a usable format from the reader and therefore could not be used I have updated my code and have it working:
Dim UserName As String
' Sets Username to current logged-in user profile
UserName = Environment.UserName
Dim JobNo As String
JobNo = Textbox1.Text
Dim listRequest As FtpWebRequest = WebRequest.Create("ftp://ftp.site.com/INPUT/" & JobNo & "_*.DBF")
listRequest.Credentials = New System.Net.NetworkCredential(“Username”, “Password”)
listRequest.Method = WebRequestMethods.Ftp.ListDirectory
Dim listResponse As FtpWebResponse = listRequest.GetResponse()
Dim reader As StreamReader = New System.IO.StreamReader(listResponse.GetResponseStream())
Dim Filedata As String = reader.ReadToEnd
Dim directory() As String = Filedata.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
For Each foundFile As String In directory
My.Computer.Network.DownloadFile("ftp://ftp.site.com/INPUT/" & foundFile, "C:\users\” & UserName & “\desktop\temp\" & foundFile, “Username”, “Password”)
Next
Updated Section
Dim reader As StreamReader = New System.IO.StreamReader(listResponse.GetResponseStream())
Dim Filedata As String = reader.ReadToEnd
Dim directory() As String = Filedata.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
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
I am trying to send a mail using Net.Mail.
The error message that I get in the line
"nClient.Send(nMail)"
is:
"Could not send mail to all recipients."
I don't know where I did something wrong.
Does anybody see my mistake?
Thank you very much!
Dim sSubject As String = "Response to your order"
Dim sBody As String = "Dear Sir or Madame, here is your invoice."
Dim sTo As String = "customer#customers.com"
Dim sFrom As String = "office#mycompany.com"
Dim sFromFriendly As String = "My super nice office team"
Dim nAtt As Net.Mail.Attachment = New Net.Mail.Attachment("C:\somepdf.pdf")
Dim nMail As New Net.Mail.MailMessage(sFrom, sTo, sSubject, sBody)
With nMail
.IsBodyHtml = False
.Bcc.Add(sFrom) 'Send a BCC to myself
.From = New MailAddress(sFrom, sFromFriendly) 'Add my nice name moniker
.Attachments.Add(nAtt) 'Add the pdf file
End With
Dim nCred As New System.Net.NetworkCredential
With nCred
.UserName = "myusername"
.Password = "mypassword"
End With
Dim nClient As New SmtpClient()
With nClient
.Host = "mywebhost"
.Port = 587
.UseDefaultCredentials = False
.Credentials = nCred
End With
nClient.Send(nMail)
nMail.Dispose()
I am using the following code for creating the folder on FTP server ; But its not working in my case :-
Dim sFilePath as string =filepath
Dim ftpResponse1 As FtpWebResponse
Dim ftpRequest1 As FtpWebRequest
Dim IsExists1 As Boolean = True
ftpRequest1 = CType(FtpWebRequest.Create(sFilePath), FtpWebRequest)
ftpRequest1.UseBinary = True
ftpRequest1.Credentials = New NetworkCredential(ZXFTPUSER, ZXFTPPASS)
ftpRequest1.UsePassive = True
ftpRequest1.Method = WebRequestMethods.Ftp.MakeDirectory
'ftpRequest1.KeepAlive = False
'ftpResponse1 = ftpRequest1.GetResponse()
'ftpResponse1 = ftpRequest1.GetResponse()
'Dim strstream1 As Stream = ftpResponse1.GetResponseStream()
'Dim strreader1 As New StreamReader(strstream1)
'Console.WriteLine(strreader1.ReadToEnd())
'strreader1.Close()
'strstream1.Close()
'ftpResponse1.Close()
Please help me.
In the above case i am not getting any error but when i am going to upload a rar file then it is giving the following exception
The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
And File Upload code is given below
Public Sub FTPUpload(ByVal SourceFile() As IO.FileInfo, ByVal folderLevel As Integer, ByVal ftpPassiveMode As Boolean)
ZXFTPPASS = "******"
Dim filePath As New IO.DirectoryInfo(filePaths)
Dim ftpRequest As FtpWebRequest
Dim dResult As Windows.Forms.DialogResult
Dim ftpFilePath As String = ""
Dim levelPath As String = ""
Dim iLoop As Integer
Dim uFile As IO.FileInfo
For Each uFile In SourceFile
Try
ftpFilePath = levelPath & "/" & uFile.Name
ftpRequest = CType(FtpWebRequest.Create(ftpFilePath), FtpWebRequest)
ftpRequest.Credentials = New NetworkCredential(ZXFTPUSER, ZXFTPPASS)
ftpRequest.UsePassive = ftpPassiveMode
ftpRequest.UseBinary = True
ftpRequest.KeepAlive = False
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
'Read in the file
Dim b_file() As Byte = System.IO.File.ReadAllBytes(filePath.FullName & "\" & uFile.Name.ToString())
'Upload the file
Dim cls_stream As Stream = ftpRequest.GetRequestStream()
cls_stream.Write(b_file, 0, b_file.Length)
cls_stream.Close()
cls_stream.Dispose()
'MsgBox("Uploaded Successfully", MsgBoxStyle.Information)
Catch
MsgBox("Failed to upload.Please check the ftp settings", MsgBoxStyle.Critical)
End Try
Next
End Sub
Looking through various sites I have found this:
Private Function FtpFolderCreate(folder_name As String, username As String, password As String) As Boolean
Dim request As Net.FtpWebRequest = CType(FtpWebRequest.Create(folder_name), FtpWebRequest)
request.Credentials = New NetworkCredential(username, password)
request.Method = WebRequestMethods.Ftp.MakeDirectory
Try
Using response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
' Folder created
End Using
Catch ex As WebException
Dim response As FtpWebResponse = DirectCast(ex.Response, FtpWebResponse)
' an error occurred
If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then
Return False
End If
End Try
Return True
End Function
this is working code on how to create a directory on a FTP server Via Vb.net
Dim folderName As String = "POP/" & Date.Now.Year.ToString & Date.Now.Month.ToString.PadLeft(2, "0"c) & Date.Now.Day.ToString.PadLeft(2, "0"c)
Dim RequestFolderCreate As Net.FtpWebRequest = CType(FtpWebRequest.Create("ftp://" & server & "/" & folderName), FtpWebRequest)
RequestFolderCreate.Credentials = New NetworkCredential(username, password)
RequestFolderCreate.Method = WebRequestMethods.Ftp.MakeDirectory
Try
Using response As FtpWebResponse = DirectCast(RequestFolderCreate.GetResponse(), FtpWebResponse)
End Using
Catch ex As Exception//catch a expection