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


'add header

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

writer.CloseStream = False
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("", toEmail, subj, body.ToString)
mm.IsBodyHtml = True
mm.Attachments.Add(New Attachment(mStream, "filename.pdf"))
Dim client As New SmtpClient()
client.Host = "yourMailHost"

'--- done, clean up resources

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

End Sub