How to send Image as email attachment using Restful service - vb.net

Below is the vb.net code that i'm using to receive an image from jquery ajax call..
Public Function MailKpiChart(ByVal img As String) As GenericResponse(Of Boolean) Implements IKPI.MailKpiChart
Dim SmtpServer As New Net.Mail.SmtpClient()
SmtpServer.Credentials = New Net.NetworkCredential("xyz#gmail.com", "password")
SmtpServer.Port = 587
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.EnableSsl = True
Dim blStatus As Boolean
Try
Dim mailMessage As New MailMessage()
mailMessage.From = New MailAddress("from#gmail.com", ".Net Devoloper")
mailMessage.To.Add(New MailAddress("to#gmail.com"))
mailMessage.Subject = "test mail"
mailMessage.Body = "hello world"
Dim imgStream As New MemoryStream()
Dim Image As System.Drawing.Bitmap = getImagefromBase64(img)
Dim filename As String = "sample image"
Image.Save(imgStream, System.Drawing.Imaging.ImageFormat.Png)
mailMessage.Attachments.Add(New Attachment(imgStream, filename, System.Net.Mime.MediaTypeNames.Image.Jpeg))
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network
SmtpServer.Send(mailMessage)
blStatus = True
Return ServiceUtility.BuildResponse(Of Boolean)(blStatus, String.Empty, String.Empty, 0)
Catch ex As Exception
Return ServiceUtility.BuildResponse(Of Boolean)(False, "",
ex.Message, AppConstants.ErrorSeverityCodes.HIGH)
End Try
End Function
and this is the function where i'm converting base64 string to an image
Public Function getImagefromBase64(ByVal uploadedImage As String) As Image
'get a temp image from bytes, instead of loading from disk
'data:image/gif;base64,
'this image is a single pixel (black)
Dim bytes As Byte() = Convert.FromBase64String(uploadedImage)
Dim image__1 As Image
Using ms As New MemoryStream(bytes)
ms.Write(bytes, 0, bytes.Length)
image__1 = Image.FromStream(ms)
End Using
Return image__1
End Function
and when i see my gmail inbox i c a mail with an attachment but i dont see the actual image which i've sent..i just c a blank image
Help Needed
Regards

I had the same issue and solved it by just adding the following line just before attaching the stream to the message.
imgStream.Position = 0
Regards,
Jonathan.

add your url - points to another web site
Dim bodys As String = "<html><head><title> example </title></head><body><table width='100%'>"
bodys += "<p><img width=135 height=77 src='http://www.example.com/image.gif'></p>"
bodys += "</table></body></html>"
Dim mails As New System.Net.Mail.MailMessage()
SmtpServer.Host = "127.0.0.1"
SmtpServer.Port = 25
mails = New System.Net.Mail.MailMessage()
mails.From = New System.Net.Mail.MailAddress("example#example.com")
mails.To.Add(txtEmail.Text)
mails.Subject = ""
mails.BodyEncoding = Encoding.UTF8
mails.IsBodyHtml = True
mails.Body = bodys.ToString()
SmtpServer.Send(mails)
A relative URL - points to a file within a web site
src="image.gif"
http://www.w3schools.com/tags/att_img_src.asp

Related

VB.net Crystal report export to html and send as html mail body using outlook

I am trying to send contents of a crystal report as email body using outlook application.
Here is my code in VB.net
Imports outlook = Microsoft.Office.Interop.Outlook
Dim a As String = something.ConnectionString
Dim cryRpt As ReportDocument
Dim username As String = a.Split("=")(3).Split(";")(0) 'get username
Dim password As String = a.Split("=")(4).Split(";")(0) 'get password
cryRpt = New ReportDocument()
Dim Path As String = Application.StartupPath
Dim svPath As String = Application.StartupPath & "\PDF"
If Not Directory.Exists(svPath) Then
Directory.CreateDirectory(svPath)
End If
cryRpt.Load(Path & "\Reports\dr.rpt")
CrystalReportViewer1.ReportSource = cryRpt
cryRpt.SetDatabaseLogon(username, password)
CrystalReportViewer1.Refresh()
Dim myExportOptions As ExportOptions
myExportOptions = cryRpt.ExportOptions
myExportOptions.ExportDestinationType = ExportDestinationType.DiskFile
myExportOptions.ExportFormatType = ExportFormatType.HTML40 'i tried HTML32 also
Dim html40FormatOptions As HTMLFormatOptions = New HTMLFormatOptions()
html40FormatOptions.HTMLBaseFolderName = svPath
html40FormatOptions.HTMLFileName = "dr.htm"
html40FormatOptions.HTMLEnableSeparatedPages = False
html40FormatOptions.HTMLHasPageNavigator = False
html40FormatOptions.UsePageRange = False
myExportOptions.FormatOptions = html40FormatOptions
cryRpt.Export()
Try
Dim oApp As outlook.Application
oApp = New outlook.Application
Dim oMsg As outlook.MailItem
oMsg = oApp.CreateItem(outlook.OlItemType.olMailItem)
oMsg.Subject = txtSubject.Text
oMsg.BodyFormat = outlook.OlBodyFormat.olFormatHTML
oMsg.HTMLBody = ""
oMsg.HTMLBody = getFileAsString(svPath & "\PoPrt\QuotPrt.html")
oMsg.To = txtEmailId.Text
Dim ccArray As New List(Of String)({txtCC1.Text, txtCC2.Text, txtCC3.Text})
Dim cclis As String = String.Join(",", ccArray.Where(Function(ss) Not String.IsNullOrEmpty(ss)))
oMsg.CC = cclis
oMsg.Display(True)
Catch ex As Exception
MsgBox("Something went wrong", vbExclamation)
End Try
SvFormPanel3.Visible = False
the function
Private Function getFileAsString(ByVal file As String) As String
Dim reader As System.IO.FileStream
Try
reader = New System.IO.FileStream(file, IO.FileMode.Open)
Catch e As Exception
MsgBox("Something went wrong. " + e.Message, vbInformation)
End Try
Dim resultString As String = ""
Dim b(1024) As Byte
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Do While reader.Read(b, 0, b.Length) > 0
resultString = resultString & temp.GetString(b)
Array.Clear(b, 0, b.Length)
Loop
reader.Close()
Return resultString
End Function
The report will get exported to the specified location as html. And when we manually open that html file it displays perfectly with border lines and all.
But when its getting added as html body of outlook application, the formatting will be gone, and looks scattered.
can anyone help
Did you try this?
Open outlook, go to, File>Options>Mail
go to section MessageFormat and untick "Reduce message size by removing format..."
I have solved the issue by exporting it into PDF and then convert to Image and embed in email body.

Attach all files in a folder to an email

I am trying to make a ConsoleApplication attach all files in a folder to an email and send it. I know how to do it with a single attachment, but for the life of me, I cannot figure out how to attach all items in a folder.
Current code:
Sub Main()
Try
Dim mail As New MailMessage("from", "to")
Dim client As New SmtpClient()
client.Port = 25
client.DeliveryMethod = SmtpDeliveryMethod.Network
client.UseDefaultCredentials = False
client.Host = ""
mail.Subject = "" + DateTime.Now.AddDays(-1).ToShortDateString()
mail.IsBodyHtml = True
mail.Body = "Test"
Dim file As System.Net.Mail.Attachment
file = New System.Net.Mail.Attachment("Path to single file")
mail.Attachments.Add(file)
client.Send(mail)
Return
Catch [error] As Exception
MsgBox("error")
Return
End Try
End Sub
Thanks in advance
EDIT:
I tried the below code that I found on another post, but it just errors out (and using the ConsoleApplication, I am not sure how to view the exact error its giving)
For Each filePath As String In Directory.GetFiles(My.Settings.FileLoc1)
Dim Attach As New Net.Mail.Attachment(filePath)
mail.Attachments.Add(Attach)
Next
I got it working!
Sub Main()
Try
Dim mail As New MailMessage("from", "too")
Dim client As New SmtpClient()
client.Port = 25
client.DeliveryMethod = SmtpDeliveryMethod.Network
client.UseDefaultCredentials = False
client.Host = ""
mail.Subject = "" + DateTime.Now.AddDays(-1).ToShortDateString()
mail.IsBodyHtml = True
mail.Body = "Test"
For Each filePath As String In Directory.GetFiles(My.Settings.FileLoc1)
Dim Attach As New Net.Mail.Attachment(filePath)
mail.Attachments.Add(Attach)
Next
client.Send(mail)
Return
Catch [error] As Exception
MsgBox("error")
Return
End Try
End Sub

Request Signature Docusign Rest API vb.net

am trying to use the DocuSign .Net Client to request a signature on a Document I am creating dynamically. So far, I have been able to change the example to vb.net and it works (Exmaple CS). I was converting the "Walkthrough #4 - Request Signature on Document", about 1/2 way down the code. Now I am trying to use the Envelope.Document I've seen in other examples, such as, DocuSign example. But it seems .Document is not part of Envelope, even thought the rest of the code in both examples translates to vb.
My other option is to use the Envelope.AddDocument but I can't seem to figure out what it's expecting. I am supposed to pass fileBytes() as Byte, fileName as String, and index As Integer. I've tried a couple different methods to get the fileBytes but keep getting an error about Invalid_Content_Type Content type is not supported.
Here is the code I've been trying. Any help on how to add a Document to an Envelope would be appreciated. Ultimately I want to be able to add multiple documents to the one envelope. I can get the env.Create(docPath) to work, but that is not helpful.
Thank you in advance for any help you can offer.
Public Function RequestEsignature(email As String, rName As String, docPath As String, strSubject As String) As String
main()
Dim AccountEmail = My.Settings.docusignUserName
Dim AccountPassword = My.Settings.docusignPassword
Dim RecipientEmail = email
Dim RecipientName = rName
Dim documentPath = docPath
Dim msgString As String
Dim acct As Account = New Account()
acct.Email = AccountEmail
acct.Password = AccountPassword
Dim result As Boolean = acct.Login()
If Not result Then
msgString = String.Format("There was an error logging in to DocuSign fo user {0}.\nError Code: {1}\nMessage: {2}", acct.Email, acct.RestError.errorCode, acct.RestError.message)
MsgBox(msgString)
Return Nothing
End If
Dim env As Envelope = New Envelope
env.Login = acct
env.Recipients = New Recipients()
Dim signer(0) As Signer
signer(0) = New Signer()
signer(0).email = email
signer(0).name = RecipientName
signer(0).routingOrder = "1"
signer(0).recipientId = "1"
env.Recipients.signers = signer
Dim envDocs = New Document()
envDocs.documentId = "1"
envDocs.name = "Test Document"
envDocs.uri = docPath
'Dim fileBytes As Byte()
'Dim fileBytes = getByteArrayII(documentPath)
'Dim oFile As FileInfo
'oFile = New FileInfo(documentPath)
'Dim oFileStream As FileStream = oFile.OpenRead()
'Dim lBytes As Long = oFileStream.Length
'If lBytes > 0 Then
' Dim fileData(lBytes - 1) As Byte
' oFileStream.Read(fileData, 0, lBytes)
'If Not env.AddDocument(fileBytes, documentPath, 0) Then
' msgString = String.Format("The was an Error adding the Document." & vbCrLf & "Error Code: {0} " & vbCrLf & "Message: {1}", env.RestError.errorCode, env.RestError.message)
' MsgBox(msgString)
' Return Nothing
'Else
' MsgBox("Doc Successfully Added")
'End If
'oFileStream.Close()
'End If
env.Status = "sent"
env.EmailSubject = strSubject
result = env.Create()
If Not result Then
If Not IsNothing(env.RestError) Then
msgString = String.Format("Error Code: {0}\nMessage: {1}", env.RestError.errorCode, env.RestError.message)
MsgBox(msgString)
Return Nothing
Else
MsgBox("There was a nondescript error while processing this request. \nPLease verify all information is correct before trying again.")
Return Nothing
End If
Else
Return env.EnvelopeId
End If
End Function
Private Function getByteArray(fileName As String) As Byte()
Dim fInfo As New FileInfo(fileName)
Dim numBytes As Long = fInfo.Length
Dim fStream As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fStream)
Dim data As Byte() = br.ReadBytes(CInt(numBytes))
br.Close()
fStream.Close()
Return data
End Function
Private Function getByteArrayII(ByVal fileName As String) As Byte()
Dim tempByte() As Byte = Nothing
If String.IsNullOrEmpty(fileName) Then
Throw New ArgumentNullException("FileName Not Provided")
Return Nothing
End If
Try
Dim fileInfo As New FileInfo(fileName)
Dim numBytes As Long = fileInfo.Length
Dim fStream As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim binaryReader As New BinaryReader(fStream)
tempByte = binaryReader.ReadBytes(Convert.ToInt32(numBytes))
fileInfo = Nothing
numBytes = 0
fStream.Close()
fStream.Dispose()
Return tempByte
Catch ex As Exception
Return Nothing
End Try
End Function
HISTORY
I am new to vb.net and programming. Thus far I have been able to make a program that allows users to enter client information with the forms being changed based on certain selections. We have a system that uses our SQL data to do mail merges in Word and then send a PDF for esignature to the client through DocuSign. We are using a SQL backend and a vb.net front end.
Lastly, I have been looking for an answer over the weekend and am now reaching out for help. I have searched google for every possible term(s) I can think to include/exclude. If I am asking publicly that truly means I have exhausted every resource I have. Please do not post links to any DocuSign Documentation as I have already visited all those sites. Thank you.
It doesn't appear that the Envelope class has a Document property, but rather a Documents property which seems to be an array.
The C# example you posted at this link seems to show how to attach a document:
// Attach the document(s) C#
envelope.Documents = new DocuSignWeb.Document[1];
DocuSignWeb.Document doc = new DocuSignWeb.Document();
doc.ID = "1";
doc.Name = "Document Name";
doc.PDFBytes = [Location of Document];
envelope.Documents[0] = doc;
Which in VB would be something like this:
'Attach the document(s) VB
envelope.Documents = new DocuSignWeb.Document(0);
Dim doc As New DocuSignWeb.Document()
doc.ID = "1"
doc.Name = "Document Name"
doc.PDFBytes = [Location of Document]
envelope.Documents(0) = doc
If this is not the problem you are facing, please provide additional details.
Clearly my approach to learning vb, api's and all the other stuff needed to get my program working is extremely daunting. I am not sure if it is my lack of knowledge or just a misunderstanding of the code, but I was finally able to get this figured out.
My function takes an object 'client' that has things like Name and Email, I also pass a list of Document Paths and the Subject line for the email. This loops through the list of documents and adds them to the envelope. I also have some examples of adding Tags which was a learning process in itself. I hope I am the only one unfortunate enough to have to be learning so many different new concepts that something this simple takes months to figure out, but if not here's the code:
'Request Signature - Send Envelope
Public Function RequestEsignature(pClient As iqClient, docPaths As List(Of String), strSubject As String) As DocuSign.Integrations.Client.Envelope
'*****************************************************************
' ENTER VALUES FOR FOLLOWING VARIABLES!
'*****************************************************************
Dim AccountEmail As String = My.Settings.docusignUserName
Dim AccountPassword As String = My.Settings.docusignPassword
Dim RecipientEmail As String = pClient.Email
Dim RecipientName As String = pClient.Name.NameFL
'*****************************************************************
' user credentials
Dim account As New Account()
account = LoginToDocusign()
If Not IsNothing(account) Then
End If
Dim result As Boolean ' = account.Login()
' create envelope object and assign login info
Dim envelope As New Envelope()
Dim recip = New Recipients()
Dim signers = New List(Of Signer)
Dim signer As New Signer()
signer.email = RecipientEmail
signer.name = RecipientName
signer.routingOrder = "1"
signer.recipientId = "1"
Dim fileBytes = New List(Of Byte())
Dim docNames = New List(Of String)
Dim iqDoc As iqPublicClasses.iqDocement
Dim docs = New List(Of Document)
Dim doc As Document
Dim tabs = New List(Of Tab)
Dim tab As New Tab()
Dim iTabs = New List(Of Tab)
Dim iTab As New Tab()
Dim dTabs = New List(Of DateSignedTab)
Dim dTab As New DateSignedTab
Dim rTabs = New List(Of RadioGroupTab)
Dim rTab As New RadioGroupTab()
Dim radios = New List(Of Radios)
Dim radio As New Radios()
tab = New Tab()
tab.anchorIgnoreIfNotPresent = True
tab.anchorString = "\s1\"
tabs.Add(tab)
dTab = New DateSignedTab
dTab.anchorIgnoreIfNotPresent = True
dTab.anchorString = "\d1\"
dTabs.Add(dTab)
iTab = New Tab()
iTab.anchorIgnoreIfNotPresent = True
iTab.anchorString = "\i1\"
iTab.anchorYOffset = 15
iTabs.Add(iTab)
iTab = New Tab()
iTab.anchorIgnoreIfNotPresent = True
iTab.anchorString = "\nri1\"
iTabs.Add(iTab)
rTab = New RadioGroupTab()
rTab.groupName = "RG1"
rTab.anchorIgnoreIfNotPresent = True
radio = New Radios()
radio.anchorString = "\rbn\"
radio.anchorIgnoreIfNotPresent = True
radio.anchorYOffset = -10
radios.Add(radio)
radio = New Radios()
radio.anchorString = "\rby\"
radio.anchorIgnoreIfNotPresent = True
radio.anchorYOffset = -10
radios.Add(radio)
rTab.radios = radios.ToArray
rTabs.Add(rTab)
signer.tabs = New Tabs()
signer.tabs.signHereTabs = tabs.ToArray
signer.tabs.dateSignedTabs = dTabs.ToArray
signer.tabs.initialHereTabs = iTabs.ToArray
signer.tabs.radioGroupTabs = rTabs.ToArray
Dim cnt = 0
For Each docName As String In docPaths
cnt += 1
iqDoc = New iqPublicClasses.iqDocement(docName)
doc = New Document()
doc.attachmentDescription = iqDoc.Name
doc.name = String.Format("{0}{1}", iqDoc.Name, iqDoc.Extension)
doc.fileExtension = iqDoc.Extension
doc.uri = iqDoc.FullPath
doc.documentId = cnt
docs.Add(doc)
docNames.Add(iqDoc.FullPath)
fileBytes.Add(File.ReadAllBytes(iqDoc.FullPath))
Next
' create envelope and send the signature request (since status is set to "sent")
envelope.Login = account
signers.Add(signer)
recip.signers = signers.ToArray
envelope.Recipients = recip
envelope.Status = "sent"
envelope.EmailSubject = strSubject
result = envelope.Create(fileBytes, docs)
If Not result Then
If envelope.RestError IsNot Nothing Then
Console.WriteLine("Error code: {0}" & vbLf & "Message: {1}", envelope.RestError.errorCode, envelope.RestError.message)
Return Nothing
Else
Console.WriteLine("Error encountered while requesting signature from template, please review your envelope and recipient data.")
Return Nothing
End If
Else
Console.WriteLine("Signature request has been sent to {0}, envelopeId is {1}.", envelope.Recipients.signers(0).email, envelope.EnvelopeId)
Return envelope
End If
End Function
PS - As I've said I am extremely new to this and am learning as I am going. I understand this may not be the most elegant approach or properly formatted code, but I unfortunately have very little time to go back an update code I've written. Hopefully one day I will be able to go back and fix all the stuff I didn't understand when I first created it.

pdf arrives damaged on when I send it via email

I want to send a pdf file via email, the file arrives but it damaged, any idea why?
Dim buffer As Byte() = New Byte(6499) {}
Dim bytesRead As Integer = 0
bytesRead = file.FileByteStream.Read(buffer, 0, buffer.Length)
Dim ms As New MemoryStream(bytesRead)
ms.Seek(0, SeekOrigin.Begin)
mail.Attachments.Add(New Attachment(ms, "test.pdf", "application/pdf"))
mail.IsBodyHtml = False
mail.From = New System.Net.Mail.MailAddress("xxxxx#gmail.com")
mail.To.Add("yyyyyy#gmail.com")
mail.Subject = "test subject"
mail.Body = "test body"
mail.Priority = System.Net.Mail.MailPriority.Normal
Dim smtp As New System.Net.Mail.SmtpClient
smtp.Host = "smtp.gmail.com"
smtp.Credentials = New System.Net.NetworkCredential("mymail#gmail.com", "pass")
smtp.Port = 587
smtp.EnableSsl = True
smtp.Send(mail)enter code here
I'm not sure from your question if you're reading the attachment in from the file system, but try changing this line:
Dim ms As New MemoryStream(bytesRead)
to this:
Dim ms = File.OpenRead("my file path")
and discard everything above it.

Mailing Attempt Object Reference?

I am trying to make a simple e-mail sending program but it has confused me when it said object reference not set to an instance of an object
Try
Dim mail As MailMessage
Dim client As SmtpClient
Dim SmtpServer As New SmtpClient()
Dim fromAddress As String
Dim toAddress1 As String
Dim toAddress2 As String
Dim toAddress3 As String
Dim subject As String
Dim message As String
SmtpServer.Credentials = New Net.NetworkCredential("*********#gmail.com", "**********")
client.UseDefaultCredentials = False
fromAddress = FromEmail.Text
If ToEmail1.Visible = True Then
toAddress1 = ToEmail1.Text
ElseIf ToEmail1.Visible = True And ToEmail2.Visible = True Then
toAddress1 = ToEmail1.Text
toAddress2 = ToEmail2.Text
ElseIf ToEmail1.Visible = True And ToEmail2.Visible = True And ToEmail3.Visible = True Then
toAddress1 = ToEmail1.Text
toAddress2 = ToEmail2.Text
toAddress3 = ToEmail3.Text
End If
subject = "Subject"
Message = "Message"
mail = New MailMessage(fromAddress, toAddress1, subject, Message)
client = New SmtpClient("Smtp.live.com")
client.Port = 587
Dim SMTPUserInfo As New System.Net.NetworkCredential("user#hotmail.com", "password")
client.Credentials = SMTPUserInfo
client.Send(mail)
MsgBox("sent")
Catch ex As Exception
MsgBox(ex.Message.ToString())
End Try
you're declaring two smtpclients
Dim client As SmtpClient
Dim SmtpServer As New SmtpClient()
you instantiated SmtpServer, but not client. Then you do
client.UseDefaultCredentials = False
I guess this is where the exception is raised.
the code looks like having some lines to send some mail through SmtpServer from a google account and other lines to send some mail through client from a hotmail account. Besides, SmtpServer is using some server defined in config.sys.