I am using the following code to generate some test files and email. When the email arrives, it has the attachment, but it is 0 size. Anyone have an idea?
Sub TestProcess(ByVal _times As Long)
Dim _book As New Workbook
'Build a sampe data table
Dim _dt As DataTable = SampleData()
For i As Long = 1 To _times
_book.Open("template.xls")
Dim _sheet As Worksheet = _book.Worksheets(0)
_sheet.Cells.ImportDataTable(_dt, False, "A1")
Dim s As System.IO.Stream = Nothing
s = _book.SaveToStream
SendEmail(s, "test.xls")
Next
End Sub
Private Function SampleData() As DataTable
Dim _dt As New DataTable
Dim _dr As DataRow
_dt.Columns.Add("row")
_dt.Columns.Add("model")
_dt.Columns.Add("serial")
_dt.Columns.Add("type")
_dt.Columns.Add("last")
For i As Integer = 1 To 5
_dr = _dt.NewRow
_dr("row") = i.ToString
_dr("model") = "Model" & i.ToString
_dr("serial") = "Serial" & i.ToString
_dr("type") = "type" & i.ToString
_dr("last") = "Last" & i.ToString
_dt.Rows.Add(_dr)
Next
Return _dt
End Function
Private Sub SendEmail(ByVal _stream As System.IO.Stream, ByVal _name As String)
Dim _body As New System.Text.StringBuilder
With _body
.AppendLine("")
.AppendLine("")
.AppendLine("body {font-family: Verdana, Arial; font-size: 8pt;}")
.AppendLine("")
.AppendLine("")
.AppendLine("")
.AppendLine("Please complete the attached spreadsheet return via fax or email.
")
.AppendLine()
.AppendLine("")
End With
Dim _msg As New MailMessage
With _msg
.Subject = "Test Request"
.IsBodyHtml = True
.Body = _body.ToString
.Attachments.Add(New Attachment(_stream, _name, "application/vnd.ms-excel"))
.From = New MailAddress("whoever@somewhere.com", "Test Request")
.To.Add(New MailAddress("me@here.com", "Me"))
End With
Dim smtp As New SmtpClient
smtp.Host = SomeServer
smtp.Send(_msg)
End Sub