VB Authenticate User In Outlook Web App - vb.net

I currently have a mail system using Microsoft's exchange server (OWA). I am trying to authenticate a user and send an email using pure Visual Basic code.
I have been trying to use a library called Aspose, however; I have no idea if I'm on the right track. I can not get it to work and I am not sure (since this is a company mail server) whether it's the server or it's my code.
Currently I have,
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Create instance of ExchangeClient class by giving credentials
Dim client As Aspose.Email.Exchange.ExchangeClient = New Aspose.Email.Exchange.ExchangeClient("https://MAILSERVER.com/username/", "username", "password", "https://MAILSERVER.com/")
' Create instance of type MailMessage
Dim msg As Aspose.Email.Mail.MailMessage = New Aspose.Email.Mail.MailMessage()
msg.From = "username#MAILSERVER.com"
msg.To = "receivingemail#gmail.com"
msg.Subject = "test"
msg.HtmlBody = "test"
' Send the message
Try
client.Send(msg)
Console.WriteLine("made it")
Catch ex As Exception
Console.WriteLine("failed")
End Try
End Sub
I have obviously changed the username, password, and server name fields to generic ones but with (what I think is the right credentials) the output is always failed.
Can anybody help me out please?

Here is what I use:
Public Shared Function SendEMail(MailMessage As System.Net.Mail.MailMessage) As String
ErrorMess = ""
' Default the from address, just in case is was left out.
If MailMessage.From.Address = "" Then
MailMessage.From = New Net.Mail.MailAddress("donotreply#MAILSERVER.com")
End If
' Check for at least one address
If MailMessage.To.Count = 0 AndAlso MailMessage.CC.Count = 0 AndAlso MailMessage.Bcc.Count = 0 Then
ErrorMess = "No Addresses Specified"
Return ErrorMess
End If
' Create a SMTP connedction to the exchange 2010 load balancer.
Dim SMTPClient As New System.Net.Mail.SmtpClient("MAILSERVER.com")
Try
Dim ValidUserCredential As New System.Net.NetworkCredential
ValidUserCredential.Domain = "MAILSERVER.com"
ValidUserCredential.UserName = My.Resources.EmailUserName
ValidUserCredential.Password = My.Resources.EmailPassword
SMTPClient.UseDefaultCredentials = False
SMTPClient.Credentials = ValidUserCredential
SMTPClient.Send(MailMessage)
Return "Mail Sent"
Catch ex As Exception
ErrorMess = ex.Message & " " & ex.InnerException.ToString
Return ErrorMess
End Try
End Function

The ExchangeClient class is used to connect to Exchange server using the WebDav protocol and is used with Exchange Server 2003 and 2007. For OWA, you need to use the IEWSClient interface as shown in the following sample code. It has an Office365 test account that you can use to send a test email (the test account is solely for testing purpose and is not property of Aspose. I just created it for assisting you in testing the functionality). Please try it and if you face any problem, you may share the porblem on Aspose.Email forum for further assistance.
' Create instance of IEWSClient class by giving credentials
Dim client As IEWSClient = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "UserTwo#ASE1984.onmicrosoft.com", "Aspose1234", "")
' Create instance of type MailMessage
Dim msg As New MailMessage()
msg.From = "UserTwo#ASE1984.onmicrosoft.com"
msg.[To] = "receiver#gmail.com"
msg.Subject = "Sending message from exchange server"
msg.IsBodyHtml = True
msg.HtmlBody = "<h3>sending message from exchange server</h3>"
' Send the message
client.Send(msg)
I work with Aspose as Developer evangelist.

Related

VB.Net Email not putting copy in sent folder

I'm going mad here!
Sending emails in VB.Net is working fine, even the read/delivery receipts are working. What it's not doing, is putting a copy of the email it sends in the sent folder. Is there something else I need to do as I've searched high a low for a solution but can't see anything.
EMail.From = New MailAddress(sSENDERaddress)
EMail.Body = sMessage
EMail.Subject = sSubject
If sAttached <> "" Then
Dim mAttachment As New Attachment(sAttached)
EMail.Attachments.Add(mAttachment)
End If
EMail.Headers.Add("Return-Receip-To", sSENDERaddress)
EMail.Headers.Add("Disposition-Notification-To", sSENDERaddress)
EMail.Headers.Add("Return-Path", sSENDERaddress)
EMail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure Or DeliveryNotificationOptions.OnSuccess ' this will send an email to the SENDER'S email address confirming that the original email was sent. If the sender doesn't get the email, then it didn't go. Simples
SMTPServer.Host = GetMailServerAddress()
SMTPServer.Port = GetMailPort()
SMTPServer.Credentials = Authentication
Try
SMTPServer.Send(EMail)
'EMail.Dispose()
bRET = True
Catch ex As Exception
''debug.Print(ex.Message)
ExceptIt(ex.Message)
'EMail.Dispose()
bRET = False
End Try
I've found a few more posts on this subject, and it looks like you can't do it. The only Heath Robinson solution is to add a BCC to my sending address...
UPDATE: For those interested, it's not an SMTP function, but an IMAP one. I suppose, if you want to, you can spend hours working the code out for this, but I found this
https://www.example-code.com/vbnet/sendWithCopyToSentMailbox.asp
Where you simply append to the sent items...
' Now use Chilkat IMAP to save the email to Inbox.Sent
Dim imap As New Chilkat.Imap
' Connect to an IMAP server.
' Use TLS
imap.Ssl = True
imap.Port = 993
success = imap.Connect("mail.mydomain.com")
If (success <> True) Then
Console.WriteLine(imap.LastErrorText)
Exit Sub
End If
' Login
success = imap.Login("myLogin","myPassword")
If (success <> True) Then
Console.WriteLine(imap.LastErrorText)
Exit Sub
End If
' The AppendMail method uploads an email to an IMAP server
' and saves it in the mailbox specified:
success = imap.AppendMail("Inbox.Sent",email)
If (success <> True) Then
Console.WriteLine(imap.LastErrorText)
Exit Sub
End If
Console.WriteLine("Mail saved to Inbox.Sent")

VBA Excel: Retrieve/display email using Gmail API on excel

I research regarding retrieving or displaying emails from gmail without using outlook and it led me here on using Gmail API. I'm confused because I don't have idea on how to solve my problem.
Here's the code:
Attribute VB_Name = "Gmail"
' Setup client and authenticator (cached between requests)
Private pGmailClient As WebClient
Private Property Get GmailClient() As WebClient
If pGmailClient Is Nothing Then
' Create client with base url that is appended to all requests
Set pGmailClient = New WebClient
pGmailClient.BaseUrl = "https://www.googleapis.com/gmail/v1/"
' Use the pre-made GoogleAuthenticator found in authenticators/ folder
' - Automatically uses Google's OAuth approach including login screen
' - Get API client id and secret from https://console.developers.google.com/
' - https://github.com/timhall/Excel-REST/wiki/Google-APIs for more info
Dim Auth As New GoogleAuthenticator
Auth.Setup CStr(Credentials.Values("Google")("id")), CStr(Credentials.Values("Google")("secret"))
Auth.AddScope "https://www.googleapis.com/auth/gmail.readonly"
Auth.Login
Set pGmailClient.Authenticator = Auth
End If
Set GmailClient = pGmailClient
End Property
' Load messages for inbox
Function LoadInbox() As Collection
Set LoadInbox = New Collection
' Create inbox request with userId and querystring for inbox label
Dim Request As New WebRequest
Request.Resource = "users/{userId}/messages"
Request.AddUrlSegment "userId", "me"
Request.AddQuerystringParam "q", "label:inbox"
Dim Response As WebResponse
Set Response = GmailClient.Execute(Request)
If Response.StatusCode = WebStatusCode.Ok Then
Dim MessageInfo As Dictionary
Dim Message As Dictionary
For Each MessageInfo In Response.Data("messages")
' Load full messages for each id
Set Message = LoadMessage(MessageInfo("id"))
If Not Message Is Nothing Then
LoadInbox.Add Message
End If
Next MessageInfo
End If
End Function
' Load message details
Function LoadMessage(MessageId As String) As Dictionary
Dim Request As New WebRequest
Request.Resource = "users/{userId}/messages/{messageId}"
Request.AddUrlSegment "userId", "me"
Request.AddUrlSegment "messageId", MessageId
Dim Response As WebResponse
Set Response = GmailClient.Execute(Request)
If Response.StatusCode = WebStatusCode.Ok Then
Set LoadMessage = New Dictionary
' Pull out relevant parts of message (from, to, and subject from headers)
LoadMessage.Add "snippet", Response.Data("snippet")
Dim Header As Dictionary
For Each Header In Response.Data("payload")("headers")
Select Case Header("name")
Case "From"
LoadMessage.Add "from", Header("value")
Case "To"
LoadMessage.Add "to", Header("value")
Case "Subject"
LoadMessage.Add "subject", Header("value")
End Select
Next Header
End If
End Function
Sub Test()
Dim Message As Dictionary
For Each Message In LoadInbox
Debug.Print "From: " & Message("from") & ", Subject: " & Message("subject")
Debug.Print Message("snippet") & vbNewLine
Next Message
End Sub
I'm using the blank file from this GitHub Link that enables this code above. I was stuck on this error:
Still I don't have the idea what's the output of this API because it's my first time using this one. I have my id and secret already from Gmail API i just removed it from the code. I guess it was really hard if I don't have someone I can do brainstorming regarding on this matter.
Hoping someone have encountered this problem or anyone is interested. Thanks.

Sending Mail with headers and saved in user's Sent Items VB.NET

I use this code to send an email using SMTP
Dim clnt As New System.Net.Mail.SmtpClient
clnt.UseDefaultCredentials = False
clnt = New System.Net.Mail.SmtpClient(gate)
Dim auth_info As System.Net.NetworkCredential = New System.Net.NetworkCredential(toAddress, pass)
'// MESSAGE SETUP
Dim msg As New System.Net.Mail.MailMessage(fromAddress, toAddress)
If msg.To.Count = 0 Then Return False
msg.CC.Clear()
'// SEND A COPY TO SENDER
'msg.Bcc.Add(auth_info.UserName)
msg.Bcc.Add(fromAddress)
'msg.DeliveryNotificationOptions = Net.Mail.DeliveryNotificationOptions.OnFailure
'msg.DeliveryNotificationOptions = Net.Mail.DeliveryNotificationOptions.OnSuccess
msg.Headers.Add("Disposition-Notification-To", fromAddress)
msg.Subject = subject
msg.Body = msgbody
msg.IsBodyHtml = True
Dim serverBusy As Boolean = True
While serverBusy
Try
clnt.Send(msg)
serverBusy = False
Catch
serverBusy = True
End Try
End While
With this code the copy of the email is sent to the sender because
of the bcc property, but in the 'incoming folder'.
Because of headers property I achieve to be informed if the receiver
read the message. A dialog box asks the receiver if he wants the
sender to be informed that he read the email message, If he
presses OK then the sender is informed with a new message. The
problem is that with this implementation the sender is asked with
the same dialog box when he opens the the copy of the message(bcc
property).

EWS Connection to Office365 fails - 401 Unauthorized

I need to make a VB .net tool to read email and save attachments. My company recently migrated from on-premise Exchange to Office 365. I have been reading EWS tutorials for 2 days now, and searching StackOverflow, but cannot get past the most basic step of authorized access to the O365 mailbox.
I took the original code from this article: htp://www.c-sharpcorner.com/UploadFile/jj12345678910/reading-email-and-attachment-from-microsoft-exchange-server/. I had some trouble converting it to VB using the Telerik converter but I think I have it right. Each time I try using the FindItemsResults method it halts with "(401) Unauthorized."
The instructions for asking a question state that I should include links to what I have already found and why it did not work, but my SO reputation only allows me 2 links. Here is what I have tried:
I have tried every possible usercode and domain combination I can think after reading this page: htps://stackoverflow.com/questions/10107872/ews-connections-issues-401-unauthorized
I am trying to read my own mailbox, so this one does not help: htps://stackoverflow.com/questions/43346498/401-unauthorized-access-when-using-ews-to-connect-to-mailbox
My connection looks identical to the connection on this page, but using it in my project did not get past the same Unauthorized error as before:htps://stackoverflow.com/questions/29009295/ews-managed-api-retrieving-e-mails-from-office365-exchange-server
Here is my code:
Public Class Form1
Public Exchange As ExchangeService
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstMsg.Clear()
lstMsg.View = View.Details
lstMsg.Columns.Add("Date", 150)
lstMsg.Columns.Add("From", 250)
lstMsg.Columns.Add("Subject", 400)
lstMsg.Columns.Add("Has Attachment", 50)
lstMsg.Columns.Add("Id", 100)
lstMsg.FullRowSelect = True
End Sub
Public Sub ConnectToExchangeServer()
Me.lblMsg.Text = "Connecting to Exchange Server"
lblMsg.Refresh()
Try
'Exchange = New ExchangeService(ExchangeVersion.Exchange2013)
Exchange = New ExchangeService()
Exchange.TraceEnabled = True
'Exchange.UseDefaultCredentials = True
Exchange.Credentials = New WebCredentials("DoeJohn", "mypasswd", "mycorp.com")
'Exchange.AutodiscoverUrl("DoeJohn#mycorp.mail.onmicrosoft.com", AddressOf MyRedirectionURLValidationCallback)
'Exchange.AutodiscoverUrl("John.Doe#mycorp.com", AddressOf MyRedirectionURLValidationCallback)
Exchange.Url = New System.Uri("https://outlook.office365.com/ews/exchange.asmx")
lblMsg.Text = "Connected to Exchange Server"
lblMsg.Refresh()
Catch ex As Exception
MsgBox("Fatal Error in Connect: " & ex.Message)
End
End Try
End Sub
Public Function MyRedirectionURLValidationCallback(RedirectionURL As String) As Boolean
Dim Result As Boolean = False
Dim RedirectionURI As Uri = New Uri(RedirectionURL)
If RedirectionURI.Scheme = "https" Then
Return True
End If
Return False
End Function
Private Sub btnRead_Click(sender As Object, e As EventArgs) Handles btnRead.Click
Call ConnectToExchangeServer()
Dim ts As TimeSpan = New TimeSpan(0, -1, 0, 0)
Dim MyDate As DateTime = DateTime.Now.Add(ts)
Dim MyFilter As SearchFilter.IsGreaterThanOrEqualTo = New SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, MyDate)
If Exchange IsNot Nothing Then
Dim FindResults As FindItemsResults(Of Item) =
Exchange.FindItems(WellKnownFolderName.Inbox, MyFilter, New ItemView(50))
Dim NewRow As ListViewItem
For Each MyItem As Item In FindResults
Dim Message As EmailMessage = EmailMessage.Bind(Exchange, MyItem.Id)
NewRow = New ListViewItem(Message.DateTimeReceived.ToString())
NewRow.SubItems.Add(Message.From.Name.ToString())
NewRow.SubItems.Add(Message.Subject)
NewRow.SubItems.Add(Message.HasAttachments.ToString())
NewRow.SubItems.Add(Message.Id.ToString())
lstMsg.Items.Add(NewRow)
Next
Else
End If
End Sub
I have confirmed that AutoDiscover is correctly finding the server, comparing to Test Email AutoConfiguration in Outlook.
AutoConfig
An interesting sidenote -- after my company moved to Office 365, I noticed that I have two new SMTP mail addresses. If I open Outlook properties on myself, I see this:
Props
This means someone can send mail to me now either at the old address john.doe#mycorp.com, and also now at doejohn#mycorp.mail.onmicrosoft.com. The new address is based on my domain usercode. I tested the microsoft one from a gmail account and it works.
To sum up, here are my questions:
1. Why am I getting the (401) Unauthorized errors when I try to read my Inbox?
2. Does Office 365 expect me to use my domain account or my mailbox name for user credentials?
3. In the domain part of the WebCredentials statement, do I use my company's mycorp.com or instead do I use Office 365's domain outlook.office365.com?
If you have read this far, many thanks!
I found the answer to the problem above, so I'll share here in case anyone needs it. The problem is down to security protocols added by my IT organization that were not documented because of recent phishing attacks on our company.
The first clue was that IT stated if I want to check company email on my personal 4G device like smartphone or ipad, I must also install Microsoft InTune for MFA connection to the O365 mail server. Since I am unaware of how to integrate InTune into my .Net app, I had to look for another answer.
I requested and was approved to move my functional mailbox from O365 to an on-premise Exchange server for this app. That solved the authentication problem.

SMTP outgoing server does not send text inside the email by vb.net

I developed apart of an application that sends emails to partners and clients with a saved email subject and text; so i used the vb.net settings to declare variables to be initiated with the program. and then asked the user to save his email subject and body to be used again later.
the problem is when i attemped to send the email, the email reaches the otherside yet with no content at all ( mail subject and body are null).
some points may be taken into consideration:
i used background worker (thread dirrent than the UI thread)
the outgoing mail is SMTP (Gmail server).
I passes the Body and the subject as strings to the sub sendmail().
Is there any better method to store mail's body and subject instead of string variables ?
I am sure that the SMTP took all my strings
Sub sendmail(receiver As String, mailsubject As String, mailbody As String, mailattachement As String)
Dim email As New System.Net.Mail.MailMessage
Dim smtp As New System.Net.Mail.SmtpClient
Try
With smtp
.EnableSsl = My.Settings.mailssl
.Port = My.Settings.mailport
.Host = My.Settings.mailhost
.Credentials = New Net.NetworkCredential(My.Settings.mailaddress, My.Settings.mailpassword)
End With
With email
.From = New System.Net.Mail.MailAddress(My.Settings.mailaddress)
.Subject = severalclientmailsubject
.Body = severalclientmailbody
.To.Add(receiver)
End With
smtp.Send(email)
Catch ex As Exception
'Generic Exception raised.
changestatus2("General Error.")
End Try
End Sub
what could can cause this thing ?!?