Asynchronously sending Emails in VB.net? - vb.net

Public Async Function SendEmail(ByVal EmailToIds As String, ByVal Subject As String, ByVal Message As String, Optional ByVal EmailCcIds As String = "", Optional ByVal MailAttachment As String = "", Optional ByVal FromEmailType As Integer = 0, Optional EmailBccIds As String = "") As Task
Dim EmailPwd() As String
Dim FromEmail, Password As String
'Dim objSmtp As SmtpClient
Dim objMail As MailMessage
Dim objAttachment As Attachment
Try
EmailPwd = GetEmailPassword(FromEmailType).Split("|")
FromEmail = EmailPwd(0)
Password = EmailPwd(1)
objMail = New MailMessage
objMail.From = New MailAddress(FromEmail)
objMail.Subject = Subject
objMail.IsBodyHtml = True
objMail.Body = Message
objMail.To.Add(EmailToIds)
If Len(EmailCcIds) > 0 Then
objMail.CC.Add(EmailCcIds)
End If
If Len(EmailBccIds) > 0 Then
objMail.Bcc.Add(EmailBccIds)
End If
If MailAttachment <> "" Then
objAttachment = New Attachment(MailAttachment)
objMail.Attachments.Add(objAttachment)
End If
Using objSmtp = New SmtpClient()
objSmtp.Host = ConfigurationSettings.AppSettings("SmtpClient")
objSmtp.DeliveryMethod = SmtpDeliveryMethod.Network
objSmtp.UseDefaultCredentials = False
objSmtp.Credentials = New NetworkCredential(FromEmail, Password)
objSmtp.Port = 587
objSmtp.EnableSsl = True
ServicePointManager.ServerCertificateValidationCallback = Function(s As Object, certificate As X509Certificate, chain As X509Chain, sslPolicyErrors As SslPolicyErrors) True
Await objSmtp.SendMailAsync(objMail)
End Using
Catch ex As Exception
Throw Ex
End Try
End Function
Getting Error : Failure sending mail.
Please help me to do this.
Thank You So much in Advance.

Related

How do I know the encoding of a webpage that I read in with vb.net?

I tried reading a webpage into my program using vb.net's HttpWebRequest. My problem has to do with figuring out the encoding of the web page before I actually read it into a string. When I read it in, some characters appear as diamonds with question-marks inside the diamonds. The web page itself looks fine in a browser, its just when I read it in that some characters aren't encoded right.
The original code I used was:
Dim myWebRequest As HttpWebRequest = WebRequest.Create(ourUri)
Dim myWebResponse As httpWebResponse = myWebRequest.GetResponse()
Then to try to get the encoding. I used:
Dim contentType As String = myWebResponse.ContentType
Dim charset As String = myWebResponse.CharacterSet
But both 'contentType' and 'charset' end up with the value 'text/html'. What I want to know is if the webpage is encoded in 'utf-8' or some other character set, so I can later retrieve it like this:
Dim receiveStream As Stream = myWebResponse.GetResponseStream()
Dim encode As Encoding = System.Text.Encoding.GetEncoding(charset)
Using reader As StreamReader = New StreamReader(receiveStream, encode)
So to sum up, there seems to be no way to inquire what the encoding is, and then use the answer to read the webpage the right way.
Is that true? Any help is appreciated.
The entire code of the routine (asked for by a commenter) follows:
Public Shared Function DownloadFileUsingURL(ByVal URLstring As String, ByVal descFilePathAndName As String, ByRef errorMessage As String, ByRef hadRedirect As Boolean,
ByRef newURL As String, ByRef isSecureConnection As Boolean, ByVal didSupplyfullfilename As Boolean, ByRef downloadedcontent As String,
ByRef httpTohttps As Boolean, ByRef httpsTohttp As Boolean, ByRef BytesRead As Integer) As Boolean
Dim ourUri As New Uri(URLstring)
Dim csh As New ClassSyncHttp
Dim expectSecureConnection As Boolean
Dim domainchanged As Boolean
newURL = ""
errorMessage = ""
hadRedirect = False
httpTohttps = False
httpsTohttp = False
isSecureConnection = False
If URLstring.ToLower.StartsWith("https:") Then
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault
expectSecureConnection = True
Else
ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault
expectSecureConnection = False
End If
Try
Dim myWebRequest As HttpWebRequest = WebRequest.Create(ourUri) ' I changed webrequest to httpwebrequest
Dim cookieContainer As CookieContainer = New CookieContainer ' needs httpwebrequest to work
myWebRequest.CookieContainer = cookieContainer
myWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
myWebRequest.UserAgent = "BrowseNet"
myWebRequest.Timeout = ClassGlobalVariables.downloadTimeoutMilliseconds
myWebRequest.Credentials = CredentialCache.DefaultCredentials
Dim myWebResponse As HttpWebResponse = myWebRequest.GetResponse()
Dim contentType As String = myWebResponse.ContentType
Dim charset As String = myWebResponse.CharacterSet
If Not ourUri.Equals(myWebResponse.ResponseUri) Then
newURL = myWebResponse.ResponseUri.ToString
hadRedirect = True
If newURL.ToLower.StartsWith("https") Then
isSecureConnection = True
End If
compareURLs(URLstring, newURL, httpTohttps, domainchanged)
End If
Dim receiveStream As Stream = myWebResponse.GetResponseStream()
If didSupplyfullfilename Then
Using fs As FileStream = File.Create(descFilePathAndName)
receiveStream.CopyTo(fs)
BytesRead = fs.Length
End Using
Else
Dim encode As Encoding = System.Text.Encoding.GetEncoding(charset)
Using reader As StreamReader = New StreamReader(receiveStream, encode)
' receiveStream.Seek(0, SeekOrigin.Begin)
downloadedcontent = reader.ReadToEnd()
BytesRead = downloadedcontent.Length
End Using
End If
myWebResponse.Close()
If expectSecureConnection Then
isSecureConnection = True
Else
isSecureConnection = False
End If
Return True
Catch ex As webException
If expectSecureConnection Then
' guessing here that the problem was that was wrong about secure connection. (Problem could be elsewhere, of course)
isSecureConnection = False
httpsTohttp = True
If ex.HResult = System.Net.WebExceptionStatus.SecureChannelFailure Then
' not sure what to do
End If
'Else
' isSecureConnection = True
End If
errorMessage = ex.Message
Return False
End Try
End Function

sending e-mail via exchange unsuccessfully

I can't find anywhere where I have a problem sending emails, it only happens to some users, while for others everything normally works with this code:
Dim service As New ExchangeService(requestedServerVersion:=ExchangeVersion.Exchange2013_SP1)
Sub SendMail(ByVal Mailadressen As List(Of String), ByVal CCAdressen As List(Of String), ByVal Betreff As String, ByVal MailText As String, ByVal Anhang As List(Of String), Optional ByVal Absender As String = "")
service.Url = New Uri("https://mail.server.com/ews/exchange.asmx")
'Add a valid user credentials
service.Credentials = New WebCredentials("someuser", "somepasw", "somedomain")
'To address the SSL challenge
ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateCertificate)
Try 'Create new message object and set properties required to send a mail
Dim sender As New Microsoft.Exchange.WebServices.Data.EmailAddress
Dim message As EmailMessage = New EmailMessage(service)
message.Subject = Betreff
message.Body = MailText
If Absender <> "" Then
Absender = Absender
sender.Address = Absender
message.From = sender
End If
For Each adr As String In Mailadressen
message.ToRecipients.Add(adr)
Next
For Each cc As String In CCAdressen
message.CcRecipients.Add(cc)
Next
For Each a As String In Anhang
message.Attachments.AddFileAttachment(a)
Next
message.SendAndSaveCopy()
Catch ex As Exception
MessageBox.Show(vbNewLine & "" & vbNewLine & String.Format("Error: {0}", ex.StackTrace))
End Try
End Sub
error I'm getting:
At Microsoft.Excange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse
(IEwsHttpWebRequest request) at
Microsoft.Excange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest
(IEwsHttpWebRequest & request
.WebServices.Data.ExchangeService.InternalCreateItems (Inumerable1
items, FolderId parentFolderId, NUllable1 messageDisposition,
NUllable1 sendInvitationsMode, ServiceErrorHandling errorHandling) at
Microsoft.Excange.WebServices.Data.Item.InternalCreate1
messageDisposition1 .WebServices.Data.EmailMessage.InternalSend
(FolderId parentFolderId, MessageDisposition messageDispostition)
can you please give me some suggestion what could be the problem here? thanks a lot

Docusign download file from template which get illegal characters in file base64string format using Chilkat and rest api

I can get file from template which passing templateid and documentid, when retrun from api , i will get as base64string format, and when i try to convert as byte,
I get an error "Additional information: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."
Here the code which i used to download file from template
Dim rest As New Chilkat.Rest
Dim success As Boolean
Dim bTls As Boolean = True
Dim port As Integer = 443
Dim bAutoReconnect As Boolean = True
success = rest.Connect("demo.docusign.net", port, bTls, bAutoReconnect)
If (success <> True) Then
Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
Debug.WriteLine(rest.LastErrorText)
Exit Sub
End If
rest.AddHeader("X-DocuSign-Authentication", "{ ""Username"": ""DocuSign#example.com"", ""Password"":""DocuSign_password"", ""IntegratorKey"":""DocuSign_Integrator_Key"" }")
Dim sbResponseBody As New Chilkat.StringBuilder
success = rest.FullRequestNoBodySb("GET", "/restapi/v2.1/accounts/xxxx/templates/xxxx-xxxx-xxxx-xxxx-xxxx/documents/x", sbResponseBody)
If (success <> True) Then
Debug.WriteLine(rest.LastErrorText)
Exit Sub
End If
Dim respStatusCode As Integer = rest.ResponseStatusCode
If (respStatusCode >= 400) Then
Debug.WriteLine("Response Status Code = " & respStatusCode)
Debug.WriteLine("Response Header:")
Debug.WriteLine(rest.ResponseHeader)
Debug.WriteLine("Response Body:")
Debug.WriteLine(sbResponseBody.GetAsString())
Exit Sub
End If
Dim jsonResponse As New Chilkat.JsonObject
jsonResponse.LoadSb(sbResponseBody)
Dim pdfBytes As Byte() = Convert.FromBase64String(sbResponseBody.ToString)
Regards,
Aravind
i changed my code from chilkat dll to Docusing dll 3.0.0 , using docusing dll i can download file from envelope, here i past my code , it will useful to some other developer.I am used .net framework code download file from file stream.
Private Function DoWnload(ByVal accessToken As String, ByVal basePath As String, ByVal accountId As String, ByVal envelopeId As String, ByVal documents As List(Of EnvelopeDocItem), ByVal docSelect As String) As String
Dim config = New Configuration(New ApiClient(basePath))
config.AddDefaultHeader("Authorization", "Bearer " & accessToken)
Dim envelopesApi As EnvelopesApi = New EnvelopesApi(config)
Dim results As System.IO.Stream = envelopesApi.GetDocument(accountId, envelopeId, docSelect)
Dim docItem As EnvelopeDocItem = documents.FirstOrDefault(Function(d) docSelect.Equals(d.DocumentId))
Dim docName As String = docItem.Name
Dim hasPDFsuffix As Boolean = docName.ToUpper().EndsWith(".PDF")
Dim pdfFile As Boolean = hasPDFsuffix
Dim docType As String = docItem.Type
If ("content".Equals(docType) OrElse "summary".Equals(docType)) AndAlso Not hasPDFsuffix Then
docName += ".pdf"
pdfFile = True
End If
If "zip".Equals(docType) Then
docName += ".zip"
End If
Dim mimetype As String
If pdfFile Then
mimetype = "application/pdf"
ElseIf "zip".Equals(docType) Then
mimetype = "application/zip"
Else
mimetype = "application/octet-stream"
End If
Dim bytesRead As Integer
Dim buffer(4096) As Byte
Using outFile As New System.IO.FileStream("C:\File.pdf", IO.FileMode.Create, IO.FileAccess.Write)
Do
bytesRead = results.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
outFile.Write(buffer, 0, bytesRead)
End If
Loop While bytesRead > 0
End Using
Return ""
End Function
Dim envelopeDocItems As List(Of EnvelopeDocItem) = New List(Of EnvelopeDocItem) From {
New EnvelopeDocItem With {
.Name = "Combined",
.Type = "content",
.DocumentId = "combined"
},
New EnvelopeDocItem With {
.Name = "Zip archive",
.Type = "zip",
.DocumentId = "archive"
}
Thanks to Inbar Gazit...
Thanks and Regards,
Aravind
Here is an example: https://www.example-code.com/vbnet/docusign_download_envelope_document.asp
Also see the other VB.NET DocuSign examples: https://www.example-code.com/vbnet/docusign.asp

How to download files from Docusign api using vb.net

How to download files once signed by all using vb.net. I manged to send envelope with template id.So i want to get back that file using envelope id, pls provide some sampe code to retrieve back files using vb.net.
Here code what i used in vb.net
Private Function DoWnload(ByVal accessToken As String, ByVal basePath As String, ByVal accountId As String, ByVal envelopeId As String, ByVal documents As List(Of EnvelopeDocItem), ByVal docSelect As String) As String
Dim config = New Configuration(New ApiClient(basePath))
config.AddDefaultHeader("Authorization", "Bearer " & accessToken)
Dim envelopesApi As EnvelopesApi = New EnvelopesApi(config)
Dim results As System.IO.Stream = envelopesApi.GetDocument(accountId, envelopeId, docSelect)
Dim docItem As EnvelopeDocItem = documents.FirstOrDefault(Function(d) docSelect.Equals(d.DocumentId))
Dim docName As String = docItem.Name
Dim hasPDFsuffix As Boolean = docName.ToUpper().EndsWith(".PDF")
Dim pdfFile As Boolean = hasPDFsuffix
Dim docType As String = docItem.Type
If ("content".Equals(docType) OrElse "summary".Equals(docType)) AndAlso Not hasPDFsuffix Then
docName += ".pdf"
pdfFile = True
End If
If "zip".Equals(docType) Then
docName += ".zip"
End If
Dim mimetype As String
If pdfFile Then
mimetype = "application/pdf"
ElseIf "zip".Equals(docType) Then
mimetype = "application/zip"
Else
mimetype = "application/octet-stream"
End If
''Dim f1 As FileStream = New FileStream("sample.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
' Return File(results, mimetype, docName)
Dim bytesRead As Integer
Dim buffer(4096) As Byte
Using outFile As New System.IO.FileStream("C:\File.pdf", IO.FileMode.Create, IO.FileAccess.Write)
Do
bytesRead = results.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
outFile.Write(buffer, 0, bytesRead)
End If
Loop While bytesRead > 0
End Using
Return ""
End Function
Dim envelopeDocItems As List(Of EnvelopeDocItem) = New List(Of EnvelopeDocItem) From {
New EnvelopeDocItem With {
.Name = "Combined",
.Type = "content",
.DocumentId = "combined"
},
New EnvelopeDocItem With {
.Name = "Zip archive",
.Type = "zip",
.DocumentId = "archive"
}
in that docSelect what need to pass ? i passed documetid, getting error.
Regards,
Aravind
Private Function DoWork(ByVal accessToken As String, ByVal basePath As String, ByVal accountId As String, ByVal envelopeId As String, ByVal documents As List(Of EnvelopeDocItem), ByVal docSelect As String) As FileStreamResult
Dim config = New Configuration(New ApiClient(basePath))
config.AddDefaultHeader("Authorization", "Bearer " & accessToken)
Dim envelopesApi As EnvelopesApi = New EnvelopesApi(config)
Dim results As System.IO.Stream = envelopesApi.GetDocument(accountId, envelopeId, docSelect)
Dim docItem As EnvelopeDocItem = documents.FirstOrDefault(Function(d) docSelect.Equals(d.DocumentId))
Dim docName As String = docItem.Name
Dim hasPDFsuffix As Boolean = docName.ToUpper().EndsWith(".PDF")
Dim pdfFile As Boolean = hasPDFsuffix
Dim docType As String = docItem.Type
If ("content".Equals(docType) OrElse "summary".Equals(docType)) AndAlso Not hasPDFsuffix Then
docName += ".pdf"
pdfFile = True
End If
If "zip".Equals(docType) Then
docName += ".zip"
End If
Dim mimetype As String
If pdfFile Then
mimetype = "application/pdf"
ElseIf "zip".Equals(docType) Then
mimetype = "application/zip"
Else
mimetype = "application/octet-stream"
End If
Return File(results, mimetype, docName)
End Function
You will need to get the nuget from here - https://www.nuget.org/packages/DocuSign.eSign.dll/ but version 5.0.0 won't work with the code above, use version 4.3
Update: adding this additional class:
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading.Tasks
Namespace Models
Public Class EnvelopeDocItem
Public Property Name As String
Public Property Type As String
Public Property DocumentId As String
End Class
End Namespace

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.