Send email with generated PDF as attachment? - asp.net

I am using the code below to generate a PDF and save it to a location. Would it be possible to have this sent out as an email with the generated PDF attached? I am assuming the Email coding would need to be done in HTML? because it will be on a webserver. Is this possible?
Dim Doc1 As New Document
Dim path As String = "\\Server\Folder" + Session("Username") + "\"
If (Not System.IO.Directory.Exists(path)) Then
System.IO.Directory.CreateDirectory(path)
End If
Dim myUniqueFileName = String.Format("{0}.pdf", random)
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(Doc1, New FileStream(path & myUniqueFileName, FileMode.Create))
' Dim ev As New itsEvents
' pdfWrite.PageEvent = ev
Doc1.Open()
Dim test As String
test = Session("PDF")
Dim imagepath As String = Server.MapPath(".") & "/images/Header.png"
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagepath)
image.ScalePercent(70.0F)
' image.SetAbsolutePosition(36.0F, 36.0F)
Doc1.Add(image)
Doc1.Add(New Paragraph(test))
Doc1.Close()

Try this:
' Create the mail message
Dim mail As New MailMessage()
' Set the addresses
mail.From = New MailAddress("me#mycompany.com")
mail.To.Add("you#yourcompany.com")
' Set the content
mail.Subject = "This is an email"
mail.Body = "this content is in the body"
' Get some binary data
Dim data As Byte() = GetData()
' Save the data to a memory stream
Dim ms As New MemoryStream(data)
' Create the attachment from a stream. Be sure to name the data with a file and
' media type that is respective of the data
mail.Attachments.Add(New Attachment(ms, "example.txt", "text/plain"))
' Send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
Function GetData() As Byte()
' This is where you will load your data from disk or database, etc.
Dim s As String = "this is some text"
Dim data As Byte() = Encoding.ASCII.GetBytes(s)
Return data
End Function 'GetData

Related

Send Excel file to Browser Asp.net

I have been breaking my head for the last two days and can't get this to work. I have a report, which I am exporting to Excel and saving on the server file directory. That part works perfectly, I can see the file, and open it, all good. The issue relies on when I try to send it to the browser for download from the server. It does not download anything, I do see the Response Header with all the info on the browser but nothing happens.
Here's one of my many tries
Private Sub dxgvPOAll_ToolbarItemClick(source As Object, e As ASPxGridViewToolbarItemClickEventArgs) Handles dxgvPOAll.ToolbarItemClick
Select Case e.Item.Name
Case "ExportAll"
Using report As DevExpress.XtraReports.UI.XtraReport = New POs_Dashboard_Report()
Using ms As New System.IO.MemoryStream()
report.Name = "Backorder Tickets"
report.ExportOptions.PrintPreview.SaveMode = DevExpress.XtraPrinting.SaveMode.UsingSaveFileDialog
Dim xlsxExportOptions As New DevExpress.XtraPrinting.XlsxExportOptions() With {.ExportMode = DevExpress.XtraPrinting.XlsxExportMode.SingleFile, .ShowGridLines = True, .FitToPrintedPageHeight = True}
Dim folderPath As String = "~/Account/TemporaryFiles/" & Utilities.RetrieveEmployeeNumber() & "/" & Guid.NewGuid.ToString & "/"
Dim serverPath As String = Server.MapPath(folderPath)
Dim xlsxExportFilePath As String = serverPath & report.Name & ".xlsx"
Dim folderInf As New DirectoryInfo(serverPath)
If Not folderInf.Exists Then folderInf.Create()
report.ExportToXlsx(xlsxExportFilePath, xlsxExportOptions)
Try
Dim objRequest As FileWebRequest = CType(WebRequest.Create(xlsxExportFilePath), FileWebRequest)
Dim objResponse As FileWebResponse = CType(objRequest.GetResponse(), FileWebResponse)
Dim bufferSize As Integer = 1
Response.Clear()
Response.ClearHeaders()
Response.ClearContent()
Response.AppendHeader("Content-Disposition:", "attachment; filename=" & xlsxExportFilePath)
Response.AppendHeader("Content-Length", objResponse.ContentLength.ToString())
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Dim byteBuffer As Byte() = New Byte(bufferSize + 1 - 1) {}
Dim memStrm As MemoryStream = New MemoryStream(byteBuffer, True)
Dim strm As Stream = objRequest.GetResponse().GetResponseStream()
Dim bytes As Byte() = New Byte(bufferSize + 1 - 1) {}
While strm.Read(byteBuffer, 0, byteBuffer.Length) > 0
Response.BinaryWrite(memStrm.ToArray())
Response.Flush()
End While
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
Catch e1 As ThreadAbortException
Catch ex As Exception
End Try
End Using
End Using
End Select
End Sub
Here's what I see on the browser's Response-Header:

Emails' rich characters are mistranslated when read from database using MimeKit

I have a windows service written in VB.Net that downloads emails into MimeMessage objects, removes their attachments, and then writes the remains of the email to a SQL Server database. A separate ASP.Net application (using VB.Net) reads the email back into a MimeMessage object and returns it to the user upon request.
Something happens during this process that causes strange characters to appear in the output.
This question (Content encoding using MimeKit/MailKit) seemed promising, but changing the character encoding from ASCII to UTF8 etc didn't solve it.
Here’s the code that saves the email to the database:
Sub ImportEmail(exConnectionString As String)
Dim oClient As New Pop3Client()
' … email connection code removed …
Dim message = oClient.GetMessage(0)
Dim strippedMessage As MimeMessage = message
' … code to remove attachments removed …
Dim mem As New MemoryStream
strippedMessage.WriteTo(mem)
Dim bytes = mem.ToArray
Dim con As New SqlConnection(exConnectionString)
con.Open()
Dim com As New SqlCommand("INSERT INTO Emails (Body) VALUES (#RawDocument)", con)
com.CommandType = CommandType.Text
com.Parameters.AddWithValue("#RawDocument", bytes)
com.ExecuteNonQuery()
con.Close()
End Sub
And here’s the ASP.Net code to read it back to the user:
Private Sub OutputEmail(exConnectionString As String)
Dim BlobString As String = ""
Dim Sql As String = "SELECT Body FROM Emails WHERE Id = #id"
Dim com As New SqlClient.SqlCommand(Sql)
com.CommandType = CommandType.Text
com.Parameters.AddWithValue("#id", ViewState("email_id"))
Dim con As New SqlConnection(exConnectionString)
con.Open()
com.Connection = con
Dim da As New SqlClient.SqlDataAdapter(com)
Dim dt As New DataTable()
da.Fill(dt)
con.Close()
If dt.Rows.Count > 0 Then
Dim Row = dt.Rows(0)
BlobString = Row(0).ToString()
Dim MemStream As MemoryStream = GetMemoryStreamFromASCIIEncodedString(BlobString)
Dim message As MimeMessage = MimeMessage.Load(MemStream)
BodyBuilder.HtmlBody = message.HtmlBody
BodyBuilder.TextBody = message.TextBody
message.Body = BodyBuilder.ToMessageBody()
Response.ContentType = "message/rfc822"
Response.AddHeader("Content-Disposition", "attachment;filename=""" & Left(message.Subject, 35) & ".eml""")
Response.Write(message)
Response.End()
End If
End Sub
Private Function GetMemoryStreamFromASCIIEncodedString(ByVal BlobString As String) As MemoryStream
Dim BlobStream As Byte() = Encoding.ASCII.GetBytes(BlobString) ' **
Dim MemStream As MemoryStream = New MemoryStream()
MemStream.Write(BlobStream, 0, BlobStream.Length)
MemStream.Position = 0
Return MemStream
End Function
For example, let’s say the text below appears in the original email:
“So long and thanks for all the fish” (fancy quotes)
When read back, it appears as follows:
†So long and thanks for all the fishâ€
Other character replacements are as follows:
– (long dash) becomes –
• (bullets) become •
The problem is with the following snippet:
If dt.Rows.Count > 0 Then
Dim Row = dt.Rows(0)
BlobString = Row(0).ToString() ' <-- the ToString() is the problem
Dim MemStream As MemoryStream = GetMemoryStreamFromASCIIEncodedString(BlobString)
Dim message As MimeMessage = MimeMessage.Load(MemStream)
To fix the data corruption, what you need to do is this:
If dt.Rows.Count > 0 Then
Dim Row = dt.Rows(0)
Dim BlobString as Byte() = Row(0)
Dim MemStream As MemoryStream = new MemoryStream (BlobString, False)
Dim message As MimeMessage = MimeMessage.Load(MemStream)
You can also get rid of your GetMemoryStreamFromASCIIEncodedString function.
(Note: I don't know VB.NET, so I'm just guessing at the syntax, but it should be pretty close to being right)

Can't retrive image from mdb database this program show error "parameter in not valid"

Try
'connection string
Dim dbpath As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
dbpath = New Uri(dbpath).LocalPath
Dim my_connection As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=D:\DataBase\KhandagramPS.mdb"
Dim userTables As DataTable = Nothing
Dim connection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection()
Dim DR As OleDbDataReader
'Dim source As String
'query string
Dim my_query As String = "SELECT sl_no,f_name,dob,sex,add,reg,[class],a_date,a_per,r_a_per,f_status,[name],photo,document FROM " & TextBox2.Text & " where sl_no=" & TextBox3.Text & " ;"
'create a connection
Dim my_dbConnection As New OleDbConnection(my_connection)
my_dbConnection.Open()
'create a command
Dim my_Command As New OleDbCommand(my_query, my_dbConnection)
DR = my_Command.ExecuteReader()
While (DR.Read())
txtslno.Text = (DR(0).ToString())
txtfname.Text = (DR(1).ToString())
Date1.Text = (DR(2).ToString())
comsex.Text = (DR(3).ToString())
txtadd.Text = (DR(4).ToString())
txtreg.Text = (DR(5).ToString())
comclass.Text = (DR(6).ToString())
Date2.Text = (DR(7).ToString())
txtaper.Text = (DR(8).ToString())
txtraper.Text = (DR(9).ToString())
txtfstatus.Text = (DR(10).ToString())
txtname.Text = (DR(11).ToString())
Dim ImageBuffer = CType(DR(12), Byte())
Dim imgStrm As New MemoryStream(ImageBuffer, True)
imgStrm.Write(ImageBuffer, 0, ImageBuffer.Length)
Dim img As Image = Image.FromStream(imgStrm)
PictureBox1.Image = img
End While
'close connection
my_dbConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
I suspect some error in your Byte-Array to Image conversion. Make sure that your Byte-Array is not messed up. Use this function instead.
Private Function getImage(imageBuffer as Byte())
Using ms as new IO.MemoryStream(imageBuffer)
Dim img = ImageIO.FromStream(ms)
Return img
End Using
End Function
my 2 cents: you shouldn't store images in an mdb file (unless things have changed a lot in the past few years). store images in a separate directory and store the file paths in the mdb so the image can be found when needed.

How to use ASPxFileManager 'SelectedFiles' property to attach files to MailMessage?

I am using DevExpress tools, specifically the FileManager which has a 'SelectedFiles' property which returns all the data needed to (add,insert,delete,retrieve, modify the record). However I can not figure out how to use the selectedfiles as a MailMessage.Attachment. The code below works to send the email, I've changed the credentials and host values for security. I just need some direction or thought on how to use the FileManager collection that is generated via 'SelectedFiles' and add them as an attachment to the email. I would really like to Zip the files if possible, but at this point simply attaching them is fine. Any thoughts?
Dim fileManager As ASPxFileManager = TryCast(sender, ASPxFileManager)
If ASPxFileManager1.SelectedFiles IsNot Nothing AndAlso ASPxFileManager1.SelectedFiles.Length > 0 Then
For i As Integer = 0 To ASPxFileManager1.SelectedFiles.Length - 1
Dim file = ASPxFileManager1.SelectedFiles.ToString
Dim attachments As New Attachment(fileManager.SelectedFiles.ToString)???
Next
End If
Try
Dim mail As New MailMessage("noreply", DropDownEdit.Text)
Dim smtp_Server As New SmtpClient("host") With {.Credentials = New Net.NetworkCredential("username", "password")}
mail.Subject = "SUBJECT"
mail.IsBodyHtml = False
mail.Body = "Testing"
smtp_Server.Send(mail)
successLabel.Text = "Your email was sent successfully."
Catch ex As Exception
End Try
End Sub
Dim attachments As New Attachment(ReadFile(ASPxFileManager1.SelectedFiles(i)), file)
mail.Attachments.Add(attachments)
The function below was needed to Read the bytes and then attach the items to the MailMessage.
Public Function ReadFile(file__1 As FileManagerFile) As System.IO.Stream
'This function allows us to pull the bytes from the DB value to render the file.
Dim filePath As String = (file__1.RelativeName)
Dim fileData As Byte()
Using con As New SqlConnection([Global].conn)
Dim sqlCmd As New SqlCommand()
sqlCmd.Connection = con
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = file__1.Name
sqlCmd.Parameters.Add("#APIKey", SqlDbType.Int).Value = Session("_UserAPIKey")
sqlCmd.CommandText = "SELECT STATEMENT"
con.Open()
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
If sqlReader.HasRows Then
While sqlReader.Read()
fileData = CType(sqlReader(0), Byte())
End While
End If
End Using
Return New MemoryStream(fileData)
End Function

embedding image not displaying in emaill using vb.net

I am trying to display an embed an image within the body of an email. The is sent, however without the image.
Below is the code:
Dim mail As New MailMessage()
mail.[To].Add("siu07aj#reading.ac.uk")
mail.From = New MailAddress("atiqisthebest#hotmail.com")
mail.Subject = "Test Email"
Dim Body As String = "<b>Welcome to codedigest.com!!</b><br><BR>Online resource for .net articles.<BR><img alt="""" hspace=0 src=""cid:imageId"" align=baseline border=0 >"
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(Body, Nothing, "text/html")
Dim imagelink As New LinkedResource(Server.MapPath(".") & "\uploads\CIMG1443.JPG", "image/jpg")
imagelink.ContentId = "imageId"
imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64
htmlView.LinkedResources.Add(imagelink)
mail.AlternateViews.Add(htmlView)
Dim smtp As New SmtpClient()
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis
smtp.Host = ConfigurationManager.AppSettings("SMTP")
smtp.Port = 587
'smtp.EnableSsl = True
smtp.Credentials = New System.Net.NetworkCredential(ConfigurationManager.AppSettings("FROMEMAIL"), ConfigurationManager.AppSettings("FROMPWD"))
smtp.Send(mail)
In the body of the email only the following is display:
Welcome to CodeDigest.Com!!
Any idea how I can get the CIMG1443.JPG displaying?
Thanks
you could try to inline the image, by converting it to a base64-string with the following method:
Public Function ImageToBase64(image As Image, format As System.Drawing.Imaging.ImageFormat) As String
If image Is Nothing Then Return ""
Using ms As New MemoryStream()
' Convert Image to byte[]
image.Save(ms, format)
Dim imageBytes As Byte() = ms.ToArray()
' Convert byte[] to Base64 String
Dim base64String As String = Convert.ToBase64String(imageBytes)
Return base64String
End Using
End Function
Then you add the image to your HTML using something like this (where yourImage is an instance of the Image-class):
dim imageString = "<img src=""data:image/png;base64," + ImageToBase64(yourImage, ImageFormat.Png) + "="" />"
That way you would get around adding the image as resource. This worked for me in several places, even though I must admit that I haven't tryed it on hmlt emails.
Sascha

Resources