Using VB.NET to log into Windows Live Mail? - vb.net

I want to make a program that tells you if you can login to an email account or not by entering their username and password into Windows Live.
It would connect to the Hotmail server and see if the user/pass combination is correct. If it can log in, it would display a label that the account is valid, if not it would say that the account is not valid.
How would I go about doing this?
Ok here's the totally incorrect code for logging in. I kind of borrowed it from sending an email:
Dim MyMailMessage As New MailMessage
MyMailMessage.From = New MailAddress(TextBox1.Text)
MyMailMessage.To.Add(TextBox1.Text)
Dim SMTP As New SmtpClient("smtp.live.com")
SMTP.Port = 25
SMTP.EnableSsl = True
SMTP.Credentials = New System.Net.NetworkCredential("textbox1.text", "textbox2.text")
SMTP.Send(MyMailMessage) // I have no idea how to get a response here... from the live server if it gives me a correct or incorrect response...
Can someone post an example code if they have a solution to this? Because I have no idea how to make this single handingly.

dim smtp as new smtpclient("smtp.live.com",25)
dim m as new mailmessage()'message must contains from, to, etc
with smtp
.usedefaultcredentials = false 'by default this is true
.credentials = new networkcredential("usuername","password")
.enablessl = true
.ishtmlbody = true
.send(m)
'or async
'.send(m,addresof enviado)' i'm not remember well if addressof is required here
end with
public sub Enviado
msgbox("mail message sended async")
end sub

One option could be to use the WebBrowser control which would allow you to access the username and password input boxes, and would allow you to click the login button. You could then see which page the user is redirected to and that would tell you in the username/password combo is correct or not.

Use Fiddler or HTTP Analyzer to see what happens when you sign in with a Browser.
(I can give you a hand: A http post request is sent to https://login.live.com....)
All you have to do then is to mimic this request with the HttpWebRequest class in .NET.
It's important that you make your request as similar as the one from the Browser as possible.

Related

Is .net core accepting only email address from config's MailSettings and only one can be set up?

I am trying to send an email using and getting the following error:
User not local; please try a different path. The server response was:
Sender address is not valid for your login. Check your email program
settings
I have understood that the error appears because in my MailMessage object I am providing another email address for From field than the one set up in the appsettings.json
(.NET was supporting custom sender emails in MailMessage.)
The questions are:
Can I only use the email address in MailMessage.From
field that is provided in appsettings.json's MailSettings?
Can I add more than one email address to appsettings.json's MailSettings?
Is there a way to use a custom MailMessage.From email other than set up in appsettings.json's MailSettings?
MailAddress from = new MailAddress(mailRequest.FromAddress, mailRequest.FromName); // custom "form" that is causing the error
var mailMessage = new MailMessage(from, new MailAddress(mailRequest.ToAddress)) {
Subject = mailRequest.Subject,
Body = mailRequest.Body
};
await _smtpClient.SendMailAsync(mailMessage);
Thanks

Delay in sending email in ASP.NET CORE

Hi am building a web application using blazor which sends email activation link to registered users, email activation is is being sent but the problem here it takes too long(approximately 5 minutes) for the registered user to receive the activation link. here is my code.
my interface class
public interface IEmailServices
{
Task SendEmailAsync(string toAddress, string subject, string body);
}
My mail Sender Class
public class EmailSender : IEmailServices
{
public async Task SendEmailAsync(string emailDestination, string subject, string htmlMessageBody )
{
MailMessage ms = new MailMessage("myemail#domain.com", emailDestination, subject,htmlMessageBody);
ms.IsBodyHtml = true;
string user = "myemail#domain.com";
string passcode = "mypassword";
SmtpClient smtpServer = new SmtpClient("mail.domain.com");
smtpServer.Credentials = new System.Net.NetworkCredential(user, passcode);
try
{
await smtpServer.SendMailAsync(ms);
}
catch (Exception ex)
{
throw ex;
}
}
}
Here's where am sending the message
//Generate Email confirmation link
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
I want the message to be sent immediately upon registration so user can confirm email.. is there something am missing thanks in advance
You don't appear to be doing anything that would generate a huge email, so this shouldn't be taking very long. A suggestion I can make is to set up your app in a test environment, with the SMTP connection set to an email account you have access to in your configuration. (Even a gmail account would work, but you'd have to set the Gmail security appropriately.) Then, run your app in debug mode with a breakpoint at await smtpServer.SendMailAsync(ms);, and then continue (F5 in VS) forward from that call to execute SendEmail Async() and let the app continue running. This will allow confirmation that the email sent, and also give you some insight into if the issue is ahead of sending the email entirely or not. Make sure you are signed in to the email account you are testing with before you start, then hop into the email account Sent folder and check that it shows the sent email. If the email takes a long time to send, the issue is in your SMTP connection from the app. If it sends in short order but still takes forever to arrive at the recipient, it has to do with the email account(s) or the clients hooked up to them (think the Send / Receive interval in Outlook set too long), but not necessarily your application. That should help you pin the problem down so you know what you are dealing with.

How to new a new access token from a refresh token using vb.net?

I don't know if you can help me understand the right way forward with this issue. I need to provide a little bit of background first.
I have a VB.Net Console Utility that uses the Google V3 Calendar API. This utility has the following process to authenticate:
Private Function DoAuthentication(ByRef rStrToken As String, ByRef rParameters As OAuth2Parameters) As Boolean
Dim credential As UserCredential
Dim Secrets = New ClientSecrets() With {
.ClientId = m_strClientID,
.ClientSecret = m_strClientSecret
}
'm_Scopes.Add(CalendarService.Scope.Calendar)
m_Scopes.Add("https://www.googleapis.com/auth/calendar https://www.google.com/m8/feeds/ https://mail.google.com/")
Try
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, m_Scopes,
"user", CancellationToken.None,
New FileDataStore("PublicTalkSoftware.Calendar.Application")).Result()
' Create the calendar service using an initializer instance
Dim initializer As New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "~~~~~~~~~~"
}
m_Service = New CalendarService(initializer)
rStrToken = credential.Token.AccessToken.ToString()
rParameters.AccessToken = credential.Token.AccessToken
rParameters.RefreshToken = credential.Token.RefreshToken
Catch ex As Exception
' We encountered some kind of problem, perhaps they have not yet authenticated?
Return False
End Try
Return True
End Function
This part of the application process works fine. The data store file gets created and once the user has authenticated it all seems to just work find from there on. The user will be able to update the calendar without any further authenticating on there part.
Now, I also have a part of my MFC (the main application) project that sends emails for the user. This uses the following CkMainManW library.
For the most part that works too. If the user has correctly set up their credentials it is fine. However, if they are using GMail, then I do things slightly differently. This is to avoid the need to have the "Allow third party apps" option to be ticked in the Google account.
So, for GMail users, we send emails like this:
mailman.put_SmtpUsername(strUsername);
mailman.put_OAuth2AccessToken(strGoogleToken);
As you can see, I use the OAuth2AccessToken. This actual value passed is the credential.Token.AccessToken.ToString() value stored from when the user authenticated. Now, I have since understood that this actual token only lasts for one hour. This would explain why some users have to repeatedly run my calendar authentication again to get a new access token.
Clearly, when I do the calendar authentication which uses the data store file, it does something under the hood the avoid the user being asked all the time to authenticate.
Now, I have read this tutorial about using the Chilkat Library for this. I notice now that in the sample code it has a comment:
// Now that we have the access token, it may be used to send as many emails as desired
// while it remains valid. Once the access token expires, a new access token should be
// retrieved and used.
So, with all the background, how do I resolve my issue? So I have a data store file that contains the original access token from when they authorised and a refresh token. This file was created by the VB.Net command line module.
By the sounds of it, the Chilkat routine needs an access token that is valid. So, what is the right way for me to get an updated access token from the refresh token, so that when I send emails it won't fail after an hour?
Update
I am getting myself confused. I changed my code so that it called the DoAuthentification call above to get the refresh token and access token. But I am finding that the actual data store file is not getting revised. The text file is not being revised.
I have to revoke access and then do the authentication to get the data store file revised. And it is only once it has been revised that the access token will work for sending emails.
I think I have found the solution. I saw this answer:
https://stackoverflow.com/a/33813994/2287576
Based on the answer I added this method:
Private Function RefreshAuthentication(ByRef rStrAccessToken As String, ByRef rStrRefreshToken As String) As Boolean
Dim parameters As New OAuth2Parameters
With parameters
.ClientId = m_strClientID
.ClientSecret = m_strClientSecret
.AccessToken = rStrAccessToken ' Needed?
.RefreshToken = rStrRefreshToken
.AccessType = "offline"
.TokenType = "refresh"
.Scope = "https://www.googleapis.com/auth/calendar https://www.google.com/m8/feeds/ https://mail.google.com/"
End With
Try
Google.GData.Client.OAuthUtil.RefreshAccessToken(parameters)
rStrAccessToken = parameters.AccessToken
rStrRefreshToken = parameters.RefreshToken
RefreshAuthentication = True
Catch ex As Exception
RefreshAuthentication = False
End Try
End Function
I am not sure if I need to pass in the existing access token or not before refreshing. But either way, the tokens get updated and I can proceed with sending emails.
FYI, in the end it became apparent that I did not need any bespoke Refresh at all because the system manages it for you under the hood.
Private Async Function DoAuthenticationAsync() As Task(Of Boolean)
Dim credential As UserCredential
Dim Secrets = New ClientSecrets() With {
.ClientId = m_strClientID,
.ClientSecret = m_strClientSecret
}
Try
credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, m_Scopes,
"user", CancellationToken.None,
New FileDataStore("xxx.Calendar.Application"))
' Create the calendar service using an initializer instance
Dim initializer As New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "yy"
}
m_Service = New CalendarService(initializer)
Catch ex As Exception
' We encountered some kind of problem, perhaps they have not yet authenticated?
' Can we isolate that as the exception?
m_logger.Error(ex, "DoAuthenticationAsync")
Return False
End Try
Return True
End Function
I have not required any bespoke Refresh of tokens for a long time now.

twilio nuget package not sending SMS message in vb.net

Does the twilio asp.net helper library package NOT work in vb.net? I can get it to work in c# web app but not vb.net web app.
In a vb.net web application project the following code doesnt send an sms message and when stepping through with the debugger, errs on the send message line and brings up a file dialog asking for access to core.cs. The twilio library's were installed via nuget.
Public Shared Sub SendAuthCodeViaSms(ByVal number As String)
Dim twilioAccountInfo As Dictionary(Of String, String) = XmlParse.GetAccountInfoFromXmlFile("twilio")
Dim accountSid As String = twilioAccountInfo("username")
Dim authToken As String = twilioAccountInfo("password")
If (Not String.IsNullOrEmpty(accountSid) AndAlso Not String.IsNullOrEmpty(authToken)) Then
Dim client = New TwilioRestClient(accountSid, authToken)
client.SendMessage(TwilioSendNumber, ToNumber, "Testmessage from My Twilio number")
Else
'log error and alert developer
End If
End Sub
But in a C# web API project the same code sends the message as expected.
protected void Page_Load(object sender, EventArgs e)
{
const string AccountSid = "mysid";
const string AuthToken = "mytoken";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var message = twilio.SendMessage(TwilioSendNumber,ToNumber,"text message from twilio");
}
and all the sid's and tokens and phone number formats are correct, otherwise the c# one wouldnt send and I wouldnt get to the client.SendMessage part of vb.net version (client.SendSMSMessage produces the same result)
Twilio evangelist here.
I tried our your code by creating a simple VB console app and it worked for me.
The only thing I can think of is that either you are not getting your Twilio credentials correctly when parsing the XML, or the phone number you are passing into the function is not formatted correctly.
I'd suggest putting the result of call to SendMessage() into a variable and checking to see if RestException property is null:
Dim result = client.SendMessage(TwilioSendNumber, ToNumber, "Testmessage from My Twilio number")
If (Not IsNothing(result.RestException)) Then
' Something bad happened
Endif
If Twilio returns a status code greater than 400, then that will show up as an exception in the RestException property and will give you a clue as to whats going on.
If that does not work, you can always break out a tool like Fiddler to watch and see if the library is making the property HTTP request and Twilio is returning the proper result.
Hope that helps.

How to use facebook authentication with asp.net login control?

I have been digging on facebook authentication for a week. I came across so many things such as facebook_connect, Facebook C# SDK from CodePlex and other ways to connect with facebook which are absolute now. Finally after reading http://developers.facebook.com for many times, I did manage to have a login button and get user's information for facebook using the new and standard Graph API stuffs. There are in Javascript such as.
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
var name = response.name
var username = response.username
var gender = response.gender
On another world, I have Login Control and asp.net Form authentication managing the whole website.
Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
Dim userName As String = Login1.UserName
Dim password As String = Login1.Password
Dim result As Boolean = UserLogin(userName, password)
If (result) Then
e.Authenticated = True
Else
e.Authenticated = False
End If
End Sub
Private Function UserLogin(ByVal userName As String, ByVal password As String) As Boolean
//validate user // if valid, return true
//return false if invalid user
End
I can't remove all form authentication from the existing website. Facebook login should be value added feature to the website. Now the few bits I don't get is ...
How to authenticate the asp.net Form authentication when someone Login to the website using facebook Login.
How do I pass all the value in the javascript to aspx.vb to connect to database and store the information.
I understand I would need to create a new table in the database, probably called FacebookUsers. But I can't think a way that facebook authentication and asp.net Login control to work together. My website is in VB.net by the way.
*How do I pass all the value in the javascript to aspx.vb to connect to database and store the information*.
Check out the following articles they may help you out a bit.
http://www.codeproject.com/Tips/371917/Get-user-Facebook-details-in-ASP-NET-and-Csharp
1.-Don't create a new table just add a new field to your current users table...
2.-Name the Field FaceBookUID or FB_ID.
3.-Store the facebook user id .
4.-Set the default Value of the FACEBOOK UID to 0.
5.-Now you'll have a unique value between a regular user and a FacebookUser.