Friday, August 5, 2011

Create PDF file and send mail using VB.NET

Imports System.Net.Mail
Imports iTextSharp.text
Imports iTextSharp.text.pdf


'your codes go here


Protected Sub CreatePdfandSendMail(ByVal toEmail as String)
'building file data
Dim doc As New Document()
Dim mStream As New MemoryStream
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, mStream)

'capture the object

'working the document

doc.Open()

'add header

doc.Add(New Paragraph("Paragraph 1"))
doc.Add(New Paragraph(" Paragraph 2"))

writer.CloseStream = False
doc.Close()
mStream.Position = 0


'prepare to send e-mails to normal user


Dim subj As String = "Email Confirmation"
Dim body As New StringBuilder("")
body.Append("This is an automated e-mail... ")
body.Append("Please find attached....")
Dim mm As New MailMessage("norely@mydomain.net", toEmail, subj, body.ToString)
mm.IsBodyHtml = True
mm.Attachments.Add(New Attachment(mStream, "filename.pdf"))
Dim client As New SmtpClient()
client.Host = "yourMailHost"
client.Send(mm)


'--- done, clean up resources

If Not mStream Is Nothing Then
mStream = Nothing
End If
mm = Nothing
client = Nothing

End Sub