logo image not sending by mail in vb.net - asp.net

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) & "' />"

Related

How can I programmatically cancel an outlook meeting with asp.net VB?

I can programmatically create a meeting request that is sent to the user through code and appears in Outlook mail where the user can accept the request and if accepted the appointment shows on their Outlook calendar. but am having trouble figuring out how to programmatically cancel the same event.
The below code is what I am using to send the meeting invitation. It works as should and sends the request to the recipient and they can accept or decline. If accepted the appointment goes on their calendar.
Dim smtpServer As String = ConfigurationManager.AppSettings("MailServer").ToString()
Dim credentials As New NetworkCredential(ConfigurationManager.AppSettings("SMTPUser").ToString(), ConfigurationManager.AppSettings("SMTPPassword").ToString())
Dim startTime1 As String = Convert.ToDateTime("10/30/2015 11:00 AM").ToString("yyyyMMddTHHmmss")
Dim endTime1 As String = Convert.ToDateTime("10/30/2015 01:00 PM").ToString("yyyyMMddTHHmmss")
Dim smtp As New SmtpClient(smtpServer)
smtp.Credentials = credentials
Dim msg As New MailMessage()
Dim emailFrom As String = ConfigurationManager.AppSettings("EmailFrom").ToString()
Dim emailTo As String = "jd#dom.com"
msg.From = New MailAddress(emailFrom, "Scheduling System")
msg.[To].Add(New MailAddress(emailTo))
msg.Subject = "JD"
Dim strBody As New StringBuilder()
strBody.AppendLine("Appointment Confirmation")
strBody.AppendLine("Subject: JD")
strBody.AppendLine("1599")
strBody.AppendLine("Location: Exam 1")
strBody.AppendLine("Date: 10/30/2015")
strBody.AppendLine("Time: 11:00AM - 1:00PM")
msg.Body = strBody.ToString()
Dim str As New StringBuilder()
str.AppendLine("BEGIN:VCALENDAR")
'PRODID: identifier for the product that created the Calendar object
str.AppendLine("PRODID:-//CARS//Outlook MIMEDIR//EN")
str.AppendLine("VERSION:2.0")
str.AppendLine("METHOD:REQUEST")
str.AppendLine("BEGIN:VEVENT")
str.AppendLine(String.Format("DTSTART:{0:yyyyMMddTHHmmss}", startTime1))
'TimeZoneInfo.ConvertTimeToUtc("BeginTime").ToString("yyyyMMddTHHmmssZ")));
str.AppendLine(String.Format("DTSTAMP:{0:yyyyMMddTHHmmss}", DateTime.Now))
str.AppendLine(String.Format("DTEND:{0:yyyyMMddTHHmmss}", endTime1))
'TimeZoneInfo.ConvertTimeToUtc("EndTime").ToString("yyyyMMddTHHmmssZ")));
str.AppendLine(String.Format("LOCATION:{0}", "Exam 1"))
' UID should be unique.
str.AppendLine(String.Format("UID:{0}", "jd101"))
str.AppendLine(String.Format("DESCRIPTION:{0}", msg.Body))
str.AppendLine(String.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body))
str.AppendLine(String.Format("SUMMARY:{0}", msg.Subject))
str.AppendLine("STATUS:CONFIRMED")
str.AppendLine("BEGIN:VALARM")
str.AppendLine("TRIGGER:-PT15M")
str.AppendLine("ACTION:Accept")
str.AppendLine("DESCRIPTION:Reminder")
str.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY")
str.AppendLine("END:VALARM")
str.AppendLine("END:VEVENT")
str.AppendLine(String.Format("ORGANIZER:MAILTO:{0}", msg.From.Address))
str.AppendLine(String.Format("ATTENDEE;CN=""{0}"";RSVP=TRUE:mailto:{1}", msg.[To](0).DisplayName, msg.[To](0).Address))
str.AppendLine("END:VCALENDAR")
Dim ct As New System.Net.Mime.ContentType("text/calendar")
ct.Parameters.Add("method", "REQUEST")
ct.Parameters.Add("name", "meeting.ics")
Dim avCal As AlternateView = AlternateView.CreateAlternateViewFromString(str.ToString(), ct)
msg.AlternateViews.Add(avCal)
smtp.Send(msg)
The below code is what I have to CANCEL an existing meeting. It sends the notice out just like the above code does, but it does not cancel/delete/remove the meeting. Can someone point me in the right direction please. I would just like the event to be removed from the Outlook calendar when this part of the code is ran. Thanks for any help.
Dim smtpServer As String = ConfigurationManager.AppSettings("MailServer").ToString()
Dim credentials As New NetworkCredential(ConfigurationManager.AppSettings("SMTPUser").ToString(), ConfigurationManager.AppSettings("SMTPPassword").ToString())
Dim startTime1 As String = Convert.ToDateTime("10/30/2015 11:00 AM").ToString("yyyyMMddTHHmmss")
Dim endTime1 As String = Convert.ToDateTime("10/30/2015 01:00 PM").ToString("yyyyMMddTHHmmss")
Dim smtp As New SmtpClient(smtpServer)
smtp.Credentials = credentials
Dim msg As New MailMessage()
Dim emailFrom As String = ConfigurationManager.AppSettings("EmailFrom").ToString()
Dim emailTo As String = "jd#dom.com"
msg.From = New MailAddress(emailFrom, "Scheduling System")
msg.[To].Add(New MailAddress(emailTo))
msg.Subject = "JD"
Dim strBody As New StringBuilder()
strBody.AppendLine("Appointment Confirmation")
strBody.AppendLine("Subject: JD")
strBody.AppendLine("HRPO#: 1599")
strBody.AppendLine("Location: Exam 1")
strBody.AppendLine("Date: 10/30/2015")
strBody.AppendLine("Time: 11:00AM - 1:00PM")
msg.Body = strBody.ToString()
Dim str As New StringBuilder()
str.AppendLine("BEGIN:VCALENDAR")
'PRODID: identifier for the product that created the Calendar object
str.AppendLine("PRODID:-//CARS//Outlook MIMEDIR//EN")
str.AppendLine("VERSION:2.0")
str.AppendLine("METHOD:REQUEST")
str.AppendLine("BEGIN:VEVENT")
str.AppendLine(String.Format("DTSTART:{0:yyyyMMddTHHmmss}", startTime1))
'TimeZoneInfo.ConvertTimeToUtc("BeginTime").ToString("yyyyMMddTHHmmssZ")));
str.AppendLine(String.Format("DTSTAMP:{0:yyyyMMddTHHmmss}", DateTime.Now))
str.AppendLine(String.Format("DTEND:{0:yyyyMMddTHHmmss}", endTime1))
'TimeZoneInfo.ConvertTimeToUtc("EndTime").ToString("yyyyMMddTHHmmssZ")));
str.AppendLine(String.Format("LOCATION:{0}", "Exam 1"))
' UID should be unique.
str.AppendLine(String.Format("UID:{0}", "jd101"))
str.AppendLine(String.Format("DESCRIPTION:{0}", msg.Body))
str.AppendLine(String.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body))
str.AppendLine(String.Format("SUMMARY:{0}", msg.Subject))
str.AppendLine("STATUS:CANCELLED")
str.AppendLine("BEGIN:VALARM")
str.AppendLine("TRIGGER:-PT15M")
str.AppendLine("ACTION:Accept")
str.AppendLine("DESCRIPTION:Reminder")
str.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY")
str.AppendLine("END:VALARM")
str.AppendLine("END:VEVENT")
str.AppendLine(String.Format("ORGANIZER:MAILTO:{0}", msg.From.Address))
str.AppendLine(String.Format("ATTENDEE;CN=""{0}"";RSVP=TRUE:mailto:{1}", msg.[To](0).DisplayName, msg.[To](0).Address))
str.AppendLine("END:VCALENDAR")
Dim ct As New System.Net.Mime.ContentType("text/calendar")
ct.Parameters.Add("method", "CANCEL")
ct.Parameters.Add("name", "meeting.ics")
Dim avCal As AlternateView = AlternateView.CreateAlternateViewFromString(str.ToString(), ct)
msg.AlternateViews.Add(avCal)
smtp.Send(msg)
ANSWERED
To cancel the meeting and have it removed from the outlook calendar you need to change the Method from "REQUEST" to "CANCEL" for the event that sends the cancellation request.
msg.Body = strBody.ToString()
Dim str As New StringBuilder()
str.AppendLine("BEGIN:VCALENDAR")
'PRODID: identifier for the product that created the Calendar object
str.AppendLine("PRODID:-//CARS//Outlook MIMEDIR//EN")
str.AppendLine("VERSION:2.0")
'''ORIGINAL-CHANGE TO CANCEL'''
'str.AppendLine("METHOD:REQUEST")
'''NEW - CHANGE TO CANCEL'''
str.AppendLine("METHOD:CANCEL")
'''Everything else remains the same. Will work and remove meeting from calendar.'''
Currently i am using this code to send meeting to outlook..
StringBuilder OutlookBody = new StringBuilder();
string textvs = #"BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN
VERSION:1.0
BEGIN:VEVENT
LOCATION:" + Location + #"
DTSTART:" + string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", start) + #"
DTEND:" + string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", end) + #"
DESCRIPTION;ENCODING=QUOTED-PRINTABLE:=
" + OutlookBody + #"=0D=0A
SUMMARY:" + AppoitmentName + #"
PRIORITY:3
END:VEVENT
END:VCALENDAR";
And it is working fine..
How can i use the same code to cancel / remove appointment from outlook.

Send email with generated PDF as attachment?

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

how to display an image from database?

i know too that this (kind of) question has been asked and answered many times. I myself have asked this once before. But I havnt been successful yet. how do I display the image in an image control for a particular employee ID... Heres my code:
`
bind()
GridView1.Visible = "True"
Dim strQuery As String = "SELECT Image FROM EmployeeTable WHERE EmployeeID =#EmployeeID"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#EmployeeID", SqlDbType.Int).Value() = Convert.ToInt32(Request.QueryString("ImageID"))
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
**Dim bytes() As Byte = CType(dt.Rows(1)("Image"), Byte())**
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows(1)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End If`
Getting error at the line in bold. "There is no row at position 1"...
Actually I want to fetch (display) the image for a particular employee id. How does it concern a row position? I dont know why i have written that line of code. Anyway, I know there are guys who can help me with this and so I thank them in advance...
OK, Heres my code for adding the image to the database. This is working fine.
Dim imageData As Byte() = New Byte(FileUpload1.FileContent.Length) {}
FileUpload1.FileContent.Read(imageData, 0, Convert.ToInt32(FileUpload1.FileContent.Length))
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
con.Open()
If EmployeeIDTextBox.Text = "" Then
MsgBox("Please Enter EmployeeID to Add Photo")
Else
Dim com As New SqlCommand("UPDATE EmployeeTable SET IMAGE = #IM where EmployeeID='" & EmployeeIDTextBox.Text & "'", con)
Dim filePath As String = Server.MapPath(FileUpload1.FileName)
'Dim imageData As Byte() = File.ReadAllBytes(filePath)
com.Parameters.AddWithValue("#IM", imageData)
com.ExecuteNonQuery()
MsgBox("File Saved Successfully!")
End If
End Sub
And now this is my code for retrieving & displaying the same image in an image control...
bind()
GridView1.Visible = "True"
'If Request.QueryString("ImageID") IsNot Nothing Then
Dim strQuery As String = "SELECT Image FROM EmployeeTable WHERE EmployeeID =#EmployeeID"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#EmployeeID", SqlDbType.Int).Value() = Convert.ToInt32(Request.QueryString("Image"))
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
Dim bytes() As Byte = CType(dt.Rows(0)("Image"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows(1)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End IF
This is not working...
Array indexes start from 0
Use
Dim bytes() As Byte = CType(dt.Rows(0)("Image"), Byte())
How is it that you don't know why you have written that?
The code you have will prompt a user to save the image file on his pc.
It will not show the image in an image control.
U can use a Http Handler and use the below code in ProcessRequest()
int Id = Convert.ToInt32(Request.QueryString["ImgId"]);
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand(
"SELECT ImageFile FROM ImageTable WHERE ImageId = #ImgId", conn))
{
command.Parameters.Add("#ImgId", SqlDbType.Int).Value = Id ;
conn.Open();
Response.ContentType = "image/gif"; //u can set it per ur requirement
Response.BinaryWrite((byte[]) command.ExecuteScalar());
}
and then use image in your page as :
<asp:Image id="Img_Db" runat="server" ImageUrl="Image.ashx?ImgId=1"/>

A recipient must be specified error when sending email from ASP.Net

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

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