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
Related
I want to send image also with mail but not attachment I want to send like an invitation or request with company logo like a card
following is my code
Sub SenMail()
Dim mail2 As MailMessage = New MailMessage()
mail2.From = New MailAddress("erpnoreplyy#gmail.com")
mail2.To.Add("shahbaz1604a#aptechgdn.net")
mail2.Subject = "test email"
'text/html
'Dim plainview As AlternateView = AlternateView.CreateAlternateViewFromString("this is my text", Nothing, "plain/html")
'Dim htmlview As AlternateView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.<img src=cid:companylogo>", Nothing, "text/html")
Dim logo As LinkedResource = New LinkedResource("f:\\logindreuss.gif", MediaTypeNames.Image.Gif)
logo.ContentId = "MyImage"
'logo.ContentId = "logo"
Dim body As String = "" &
"<img src=cid:MyImage width='100px' height='100px' alt='logostring'>"
'"<img src='" & htmlview.ToString() & "' alt='htmlstring'>" &
'"<img src='" & plainview.ToString() & "' alt='plainstring'>"
mail2.IsBodyHtml = True
mail2.Body = body
'htmlview.LinkedResources.Add(logo)
'mail2.AlternateViews.Add(plainview)
'mail2.AlternateViews.Add(htmlview)
'Dim smtp As SmtpClient = New SmtpClient("465.0.0")
Dim av As AlternateView = AlternateView.CreateAlternateViewFromString(body, Nothing, MediaTypeNames.Text.Html)
av.LinkedResources.Add(logo)
Dim smtp As SmtpClient = New SmtpClient()
smtp.Port = 587
smtp.Host = "smtp.gmail.com"
smtp.Credentials = New System.Net.NetworkCredential("erpnoreplyy#gmail.com", "naeem1234")
smtp.EnableSsl = True
smtp.Send(mail2)
End Sub
Here you can convert your image to byte and pass it to mail body as html, If Image is still not showing then you have to decode that Base64String online and you get simple URI and put in your img tag of body
Dim b_logo = File.ReadAllBytes("C:\Users\yogesh\Pictures\sclhneider.png")
Dim body As String = "<img src='data:image/png;base64," & Convert.ToBase64String(b_logo) & "' />"
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
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
We are trying to send the out the output of a html string to a particular test email address and found this error at runtime:
A recipient must be specified.
Here is the coding from the code-behind file.
Protected Sub EmailTheList()
' Get the rendered HTML.
'-----------------------
Dim SB As New StringBuilder()
Dim SW As New StringWriter(SB)
Dim htmlTW As New HtmlTextWriter(SW)
GridViewSummary.RenderControl(htmlTW)
' Get the HTML into a string.
' This will be used in the body of the email report.
'---------------------------------------------------
Dim dataGridHTML As String = SB.ToString()
Dim SmtpServer As New SmtpClient()
SmtpServer.Credentials = New Net.NetworkCredential("myEmailAddress#gmail.com", "myPassword")
SmtpServer.Port = 587
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.EnableSsl = True
ObjMailMessage = New MailMessage()
Try
ObjMailMessage.From = New MailAddress("myEmailAddress#gmail.com", "Some text is here.", System.Text.Encoding.UTF8)
ObjMailMessage.Subject = "Test message from Emad"
ObjMailMessage.ReplyToList.Add("john.doe#example.com")
ObjMailMessage.Body = dataGridHTML
ObjMailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
SmtpServer.Send(ObjMailMessage)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
We suspect we are not using the correct syntax for this line:
ObjMailMessage.From = ObjMailMessage.ReplyToList.Add("john.doe#example.com")
You're missing the To: address, which is causing the error regarding a recipient.
ObjMailMessage.To.Add(New MailAddress("mail#somemail.com", "An error happened", System.Text.Encoding.UTF8))
Reference: http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.aspx
What are valid values for the MediaType Property on a HttpWebRequest?
I want to do something like this:
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim req As System.Net.HttpWebRequest = DirectCast(System.Net.WebRequest.Create(New Uri(url)), System.Net.HttpWebRequest)
' Add the current authentication cookie to the request
Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName)
Dim authenticationCookie As New System.Net.Cookie(FormsAuthentication.FormsCookieName, cookie.Value, cookie.Path, HttpContext.Current.Request.Url.Authority)
req.CookieContainer = New System.Net.CookieContainer()
req.CookieContainer.Add(authenticationCookie)
req.MediaType = "PRINT"
Dim res As System.Net.WebResponse = req.GetResponse()
'Read data
Dim ResponseStream As Stream = res.GetResponseStream()
'Write content into the MemoryStream
Dim resReader As New BinaryReader(ResponseStream)
Dim docStream As New MemoryStream(resReader.ReadBytes(CInt(res.ContentLength)))
Thanks.
I think this wikipedia page should give you a fairly comprehensive list of media types:
Media Types