Oauth 2.0 SMTP send email with EASendEmail VB - vb.net

Following the changes, I try to connect and send mails via EAGetMail/EASendMail.
The connection is good, I have good access to the token and also to my mailbox.
However, when I want to send an email via "smtp.office365.com" I get an error: 535 5.7.3 Authentication unsuccessful.
I do not understand where the error can come from, I take the same token as when connecting to the mailbox.
Below is just the code to send emails, I have a token and it works perfectly to connect to my email
If someone has a project that works with smtp and Oauth 2.0 (without using a browser)...
Module Module1
Sub Main(ByVal args As String())
Try
RetrieveEmail()
Catch ep As Exception
Console.WriteLine(ep.ToString())
End Try
Console.ReadKey()
End Sub
Function _generateFileName(ByVal sequence As Integer) As String
Dim currentDateTime As DateTime = DateTime.Now
Return String.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", New CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence)
End Function
Function _postString(ByVal uri As String, ByVal requestData As String) As String
Dim httpRequest As HttpWebRequest = TryCast(WebRequest.Create(uri), HttpWebRequest)
httpRequest.Method = "POST"
httpRequest.ContentType = "application/x-www-form-urlencoded"
Using requestStream As Stream = httpRequest.GetRequestStream()
Dim requestBuffer As Byte() = Encoding.UTF8.GetBytes(requestData)
requestStream.Write(requestBuffer, 0, requestBuffer.Length)
requestStream.Close()
End Using
Try
Dim httpResponse As HttpWebResponse = TryCast(httpRequest.GetResponse(), HttpWebResponse)
Using reader As New StreamReader(httpResponse.GetResponseStream())
Dim responseText = reader.ReadToEnd()
Return responseText
End Using
Catch ex As WebException
If ex.Status = WebExceptionStatus.ProtocolError Then
Dim response = TryCast(ex.Response, HttpWebResponse)
If response IsNot Nothing Then
Console.WriteLine("HTTP: " & response.StatusCode)
' reads response body
Using reader As StreamReader = New StreamReader(response.GetResponseStream())
Dim responseText As String = reader.ReadToEnd()
Console.WriteLine(responseText)
End Using
End If
End If
Throw ex
End Try
End Function
Public Sub RetrieveEmail()
Try
Dim client_id As String = "XXXXXXXXXXXXXXXXXXXX"
Dim client_secret As String = "XXXXXXXXXXXXXXXXXXXXXXXXX"
' If your application is not created by Office365 administrator,
' please use Office365 directory tenant id, you should ask Offic365 administrator to send it to you.
' Office365 administrator can query tenant id in https://portal.azure.com/ - Azure Active Directory.
Dim tenant As String = "XXXXXXXXXXXXXXXXXX"
Dim requestData As String = String.Format("client_id={0}&client_secret={1}&scope=https://outlook.office365.com/.default&grant_type=client_credentials",
client_id, client_secret)
Dim tokenUri As String = String.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenant)
Dim responseText As String = _postString(tokenUri, requestData)
Dim parser As EASendMail.OAuthResponseParser = New EASendMail.OAuthResponseParser()
parser.Load(responseText)
Dim officeUser As String = "tma#XXXX.fr"
Dim oServerSend As SmtpServer = New SmtpServer("smtp.office365.com")
oServerSend.ConnectType = SmtpConnectType.ConnectSSLAuto
oServerSend.Port = 587
oServerSend.AuthType = SmtpAuthType.XOAUTH2
oServerSend.User = officeUser
oServerSend.Password = parser.AccessToken
Dim oMailSend As SmtpMail = New SmtpMail("TryIt")
oMailSend.From = "tma#XXX.fr"
' Please change recipient address to yours for test
oMailSend.[To] = "XXXXXXXXXXX"
oMailSend.Subject = "test email from Hotmail account with OAUTH 2"
oMailSend.TextBody = "this is a test email sent from VB.NET project with Hotmail."
Console.WriteLine("start to send email using OAUTH 2.0 ...")
Dim oSmtp As SmtpClient = New SmtpClient()
oSmtp.SendMail(oServerSend, oMailSend)
' Quit and expunge emails marked as deleted from server.
Console.WriteLine("Completed!")
Catch ep As Exception
Console.WriteLine(ep.ToString())
End Try
End Sub
End Module

Related

Reading Rest API Call Response Status Code in VB.NET

I am a beginner in the API ecosystem. I am using VB.NET to call API. Code used for the same given below:
Try
Dim s As HttpWebRequest
Dim enc As UTF8Encoding
Dim postdata As String
Dim postdatabytes As Byte()
Dim jo As New JObject
jo.Add("apiid", objProp.Text7)
jo.Add("apiData", objProp.Text8)
postdata = jo.ToString()
s = HttpWebRequest.Create(objProp.Text6)
enc = New System.Text.UTF8Encoding()
postdatabytes = enc.GetBytes(postdata)
s.Method = "POST"
s.ContentType = "application/json"
s.ContentLength = postdatabytes.Length
s.Headers.Add("user-name", "MjRKQGU1NypQJkxZYVpCdzJZXnpKVENmIXFGQyN6XkI=")
s.Headers.Add("api-key", "UjMhTDZiUlE1MkhMWmM2RkclJXJhWUJTTWZDeHVEeDQ=")
Using stream = s.GetRequestStream()
stream.Write(postdatabytes, 0, postdatabytes.Length)
End Using
Dim result = s.GetResponse()
Dim responsedata As Stream = result.GetResponseStream
Dim responsereader As StreamReader = New StreamReader(responsedata)
Dim xResponse = responsereader.ReadToEnd
Try
Dim opData = JObject.Parse(xResponse)("apiData").ToString
objProp = JsonConvert.DeserializeObject(Of default_prop)(opData)
Catch ex As Exception
End Try
Catch myerror As OracleException
'Status
objProp.Text5 = "500"
'Failure Response Message
objProp.Text11 = "Internal Server Error..."
db_close()
End Try
My issue is that I could not find the proper syntax to retrieve API Response Status Code from the response. Request your guidance
With some small changes on your code you can do the trick as follow:
'....... other code here
Using stream = s.GetRequestStream()
stream.Write(postdatabytes, 0, postdatabytes.Length)
End Using
Dim result As HttpWebResponse = CType(s.GetResponse(), HttpWebResponse)
Console.WriteLine(result.StatusCode)

Acessing Google Calendar API from Windows Service

I am writing a windows service application in Visual Studio (VB) that polls a users google calendar for any events that are happening within the next 5 minutes.
Ideally, I'd like my service to generate the credentials, but I don't think a windows service can pop up a browser page to authenticate someone. Currently I am generating the credentials in a specific location from a console app that can pop up a browser, and having the service look for credentials in that location. I'd like to get rid of the console app altogether, but if it's necessary I'll just run it in the batch file that installs the service.
The big issue I'm having is generating the credentials file (secondary concern), and more importantly refreshing it so it doesn't expire after an hour (primary concern).
Here is my windows service code (this works perfectly fine for the hour after I run my console app and allow access to my calendar):
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Private Sub writeUpdateTimerEvent(source As Object, e As ElapsedEventArgs)
Dim credential As UserCredential
Try
Using stream = New FileStream("FILE PATH TO client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "FILE PATH TO WHERE MY CONSOLE APP IS STORING THE CREDENTIALS FILE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
If credential Is Nothing Then
credential.RefreshTokenAsync(CancellationToken.None)
End If
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.TimeMax = DateTime.Now.AddMinutes(5)
request.ShowDeleted = False
request.SingleEvents = True
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim eventsString As String = ""
Dim events As Events = request.Execute()
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
'This is where I do my operations on events occuring in the next 5 minutes
EventLog1.WriteEntry("Event occuring within 5 minutes")
Else
EventLog1.WriteEntry("No event occuring within 5 minutes")
End If
Catch ex As Exception
EventLog1.WriteEntry("error grabbing events." & Environment.NewLine & ex.message)
End Try
End Sub
Here is my console app code (pretty much the same as above):
Module Module1
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Sub Main()
Dim credential As UserCredential
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "SAME FILE PATH AS IN MY SERVICE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.ShowDeleted = False
request.SingleEvents = True
request.MaxResults = 10
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim events As Events = request.Execute()
Console.WriteLine("Upcoming events:")
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
For Each eventItem As Object In events.Items
Dim [when] As String = eventItem.Start.DateTime.ToString()
If [String].IsNullOrEmpty([when]) Then
[when] = eventItem.Start.[Date]
End If
Console.WriteLine("{0} ({1})", eventItem.Summary, [when])
Next
Console.WriteLine("You may now close this window.")
System.Environment.Exit(0)
Else
Console.WriteLine("No upcoming events found.")
End If
Console.Read()
End Sub
End Module
Got it working now, using a service account instead of a user account. No need for dealing with generating credentials or refreshing the token.
Dim serviceAccountEmail As [String] = ConfigurationManager.AppSettings("ServiceAcct")
Dim certificate = New X509Certificate2("key.p12", "notasecret", X509KeyStorageFlags.Exportable)
Dim credential1 As New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = Scopes
}.FromCertificate(certificate))
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential1,
.ApplicationName = ApplicationName
})

how to get source code from link with user name and password in vb or c#

i try to get code source from my facebook account bet i get only the login page code source...
i assumes its happens because problem with cookie
my code...
'download data from url and return string of the source code
Public Shared Function getSourceCode(address As String) As String
Dim reader As StreamReader = Nothing
'Address of URL
Dim URL As String = address
' Get HTML data
Dim client As WebClient = New WebClient()
Try
client.Proxy = Nothing
Dim data As Stream = client.OpenRead(URL)
reader = New StreamReader(data)
Catch
'error
End Try
If reader IsNot Nothing Then Return reader.ReadToEnd
Return ""
End Function

Dropnet code in vb not working

I'm trying to use dropnet for file upload on Dropbox in vb, but does not work. Results the following error: Received Response [Unauthorized]: Expected to see [OK]. The HTTP response was [{"error": "Request token not found."}]
Here is my code:
_client = New DropNetClient("xxxxxxx", "xxxxxxx")
Dim login As UserLogin = _client.GetToken()
_client.UserLogin = login
Dim url = _client.BuildAuthorizeUrl()
Process.Start(url)
Dim tokenAcess = _client.GetAccessToken()
_client.GetAccessTokenAsync(Function(accessToken)
_client = New DropNetClient("xxxxxx", "xxxxxx", tokenAcess)
End Function, Function([error]) MessageBox.Show([error].Message)
End Function)
Try
Dim rawData As Byte() = File.ReadAllBytes("c:\image.png")
Dim result As MetaData = _client.UploadFile("/", "image.png", rawData)
MessageBox.Show("Successfully uploaded to Dropbox.", "Uploaded to Dropbox")
Catch dropboxEx As Exception
MessageBox.Show("Error: " + dropboxEx.Message)
End Try

Creating webrequest POST for Twitter API using VB.NET

There are quite a few Twitter API related posts, but none seem to answer my questions directly.
I know how to send an HttpWebRequest as POST.
I am fairly sure I need to send the webrequest to: "https://api.twitter.com/1/statuses/update.json" (not totally clear)
I know there are many libraries out there that all you have to do is pass your consumer keys and token keys. However, I need to create some very short code, in a function, that simple posts a hard coded string to Twitter. When I get this working that hard coded string will be replaced by variable.
I've no need to status updates or any kind of information from Twitter. Just POST "Hello World!" to start with, and I can go from there.
I am forced to use VB.NET. I am using Visual Studio Web Developer 2010.
Now, that all said, I have looked at Nikolas Tarzia's VB.NET port of C-Sharp code here:
http://oauth.googlecode.com/svn/code/vbnet/oAuth.vb
I can see roughly what the functions do by looking at them, but have no idea which ones I need to call to create a webresponse and send to Twitter! Also I believe this code contains more than I need. If I just want to create a POST, then likely I only need to hash function and the nonce function and my tokens and keys. Is that right? If so, could someone please help me narrow this down? In the process helping me understand a bit better what properly formed webrequest needs to be sent to Twitter to make a quick Tweet?
Thanks,
Will
PS - I finally put together some code, based on looking at OAuth documentation, a neat little code example on using POST request in VB, and the Twitter Developer area OAuth tool to generate some Base String for the request. Unfortunately while it compiles and runs okay, I am not getting a tweet. Could someone have a look at the code and see if they can spot any glaring issues? Obviously I replaced my tokens and consumer keys with "xxxxx". All I want for Christmas is to run this code and make a quick Tweet on my Twitter account! ;)
Public Shared Function Tweet(strText As String) As Boolean
Dim boolResult As Boolean = False
Dim urlAddress As Uri = New Uri("https://api.twitter.com/1/statuses/update.json")
Dim strData As StringBuilder
Dim byteData() As Byte
Dim postStream As Stream = Nothing
Dim strConsumerKey As String = "xxxxxx"
Dim strConsumerSecret As String = "xxxxxx"
Dim strAccessToken As String = "xxxxxx"
Dim strAccessTokenSecret As String = "xxxxxx"
Dim objRequest As HttpWebRequest
Dim objResponse As HttpWebResponse = Nothing
Dim objReader As StreamReader
Dim objHeader As HttpRequestHeader = HttpRequestHeader.Authorization
Try
objRequest = DirectCast(WebRequest.Create(urlAddress), HttpWebRequest)
objRequest.Method = "POST"
objRequest.ContentType = "application/x-www-form-urlencoded"
strData = New StringBuilder()
strData.Append("&Hello_World%2521%3D%26oauth_consumer_key%3D" + strConsumerKey + "%26oauth_nonce%3Dda6bb8ce7e48547692f4854833afa680%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1329746260%26oauth_token%3D" + strAccessToken + "%26oauth_version%3D1.0")
objRequest.Headers.Add(objHeader, "Authorization: OAuth oauth_consumer_key=""xxxx"", oauth_nonce=""da6bb8ce7e48547692f4854833afa680"", oauth_signature=""xxxx"", oauth_signature_method=""HMAC-SHA1"", oauth_timestamp=""1329750426"", oauth_token=""xxxx"", oauth_version=""1.0""")
' Create a byte array of the data we want to send
byteData = UTF8Encoding.UTF8.GetBytes(strData.ToString())
' Set the content length in the request headers
objRequest.ContentLength = byteData.Length
Try
postStream = objRequest.GetRequestStream()
postStream.Write(byteData, 0, byteData.Length)
Finally
If Not postStream Is Nothing Then postStream.Close()
End Try
boolResult = True
Catch ex As Exception
boolResult = False
HttpContext.Current.Session.Add("Error", ex.ToString())
End Try
Try
' Get response
objResponse = DirectCast(objRequest.GetResponse(), HttpWebResponse)
' Get the response stream into a reader
objReader = New StreamReader(objResponse.GetResponseStream())
' Console application output
Console.WriteLine(objReader.ReadToEnd())
Finally
If Not objResponse Is Nothing Then objResponse.Close()
End Try
Return boolResult
End Function
I´ve made this class to post in twitter using API1.1.
It expects the oauth token, oauth token secret, oauth "consumer" key (this means API key) and oauth consumer secret (this means API secret) in the constructor. If you want to post in your own account, the four values will be in the API keys tab of your application in https://apps.twitter.com/. If you want to post on your visitors account you'll have to create some extra code to redirect them to twitter for login and get the access token.
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text
Imports System.Security.Cryptography
Imports System.Net
Imports System.IO
Public Class SBTwitter
Private oauth_token As String
Private oauth_token_secret As String
Private oauth_consumer_key As String
Private oauth_consumer_secret As String
Public Sub New(ByVal APIKey As String, ByVal APISecret As String, ByVal oauthToken As String, ByVal oauthTokenSecret As String)
oauth_token = oauthToken
oauth_token_secret = oauthTokenSecret
oauth_consumer_key = APIKey
oauth_consumer_secret = APISecret
End Sub
Public Function PostInTwitter(ByVal post As String) As String
Try
Dim oauth_version = "1.0"
Dim oauth_signature_method = "HMAC-SHA1"
Dim oauth_nonce = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim timeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, _
0, DateTimeKind.Utc)
Dim oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim resource_url = "https://api.twitter.com/1.1/statuses/update.json"
Dim status = post
Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" & "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}"
Dim baseString = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, _
oauth_version, Uri.EscapeDataString(status))
baseString = String.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString))
Dim compositeKey = String.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret))
Dim oauth_signature As String
Using hasher As New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
End Using
Dim headerFormat = "OAuth oauth_nonce=""{0}"", oauth_signature_method=""{1}"", " & "oauth_timestamp=""{2}"", oauth_consumer_key=""{3}"", " & "oauth_token=""{4}"", oauth_signature=""{5}"", " & "oauth_version=""{6}"""
Dim authHeader = String.Format(headerFormat, Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_token), _
Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_version))
Dim postBody = "status=" & Uri.EscapeDataString(status)
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(resource_url), HttpWebRequest)
request.Headers.Add("Authorization", authHeader)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Using stream As Stream = request.GetRequestStream()
Dim content As Byte() = ASCIIEncoding.ASCII.GetBytes(postBody)
stream.Write(content, 0, content.Length)
End Using
Dim response As WebResponse = request.GetResponse()
Return response.ToString
Catch ex As Exception
Return ex.Message
End Try
End Function
End Class