Can't authenticate with SMTP (but IMAP works) Microsoft 365 - vb.net

I'm trying to create an 'automation#mydomain.com' email account, which will be used to send out email alerts from my code. Since the days of 'basic authentication' are done, I'm implementing this with 'modern authentication'. Everything is hosted in Microsoft 365. Authentication is using the latest MSAL. Email is handled using the recommended MailKit library.
The Code
This code is trying to do four things:
Read a certificate from a file.
Use that certificate to get an authentication token from Microsoft.
Test that token and the configuration by opening an IMAP connection to the desired inbox and reading out the number of messages inside.
Send an email.
Dim AuthCert = New X509Certificate2(CertPath, EmailSettings("AuthCertPassword"), X509KeyStorageFlags.PersistKeySet)
AuthClient = ConfidentialClientApplicationBuilder.Create(EmailSettings("ApplicationID")).
WithAuthority(AzureCloudInstance.AzurePublic, EmailSettings("TenantID")).
WithCertificate(AuthCert).
Build
Dim AuthResult = AuthClient.AcquireTokenForClient({"https://outlook.office365.com/.default"}).ExecuteAsync.Result
Dim EmailMessage As New MimeMessage
EmailMessage.From.Add(New MailboxAddress(Nothing, Config.EmailSenderAddress))
For Each R In Config.EmailRecipients
EmailMessage.To.Add(New MailboxAddress(Nothing, R))
Next
EmailMessage.Body = New TextPart("plain") With {.Text = Warning}
Using MailClient As New ImapClient
MailClient.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect)
Log.WriteEntry($"Token length is: {AuthResult.AccessToken.Length}")
Dim Authentication As New SaslMechanismOAuth2(Config.EmailSenderAddress, AuthResult.AccessToken)
MailClient.Authenticate(Authentication)
MailClient.Inbox.Open(MailKit.FolderAccess.ReadOnly)
Log.WriteEntry($"IMAP worked. Inbox count is {MailClient.Inbox.Count}")
MailClient.Disconnect(True)
End Using
Using MailClient As New SmtpClient
MailClient.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls)
Dim Authentication As New SaslMechanismOAuth2(Config.EmailSenderAddress, AuthResult.AccessToken)
MailClient.Authenticate(Authentication)
MailClient.Send(EmailMessage)
MailClient.Disconnect(True)
End Using
The above code almost works.
Read certificate file ✔
Get a working authentication token ✔
Connect via IMAP to read number of emails in the inbox ✔
Send an email via SMTP ✖
The error message is:
MailKit.Security.AuthenticationException: 535: 5.7.3 Authentication unsuccessful [BN9PR03CA0500.namprd03.prod.outlook.com 2023-01-26T16:58:30.103Z 08DAFF3B69EFD03B]
It occurs on the line: MailClient.Authenticate(Authentication) in the Smtp section.
Note that this same exact authentication succeeded when used for IMAP.
The M365 Config
I have followed two Microsoft articles in setting up my cloud-side configuration. The first article is:
Authenticate an IMAP, POP or SMTP connection using OAuth
I have registered the application and given it the required API permissions:
I don't have to worry about the workings of SASL XOAUTH2 because the MailKit library implements that for me.
I have created the 'service principal' using the New-ServicePrincipal command (using the correct Object ID from the Enterprise Application node). And have run the Add-MailboxPermission command to grant that principal access to the mailbox.
I have also followed the steps from this article:
Enable or disable authenticated client SMTP submission (SMTP AUTH) in Exchange Online
SMTP Authorization is disabled at the organization level. But that setting has been overridden for this specific mailbox using the Set-CASMailbox command.
So, what am I missing?

It might be temporary server issue with Microsoft OAuth that is ongoing for several day now. Many many reports from ppl with different email clients report for the same issue. For example
https://support.emclient.com/index.php?/Knowledgebase/Article/View/256/7/cannot-send-emails-for-outlookcom-accounts---authentication-aborted

Related

outgoing mail server on odoo

I have created a record on "ir.mail_server" model which is the outgoing mail server model. configured as:
SMTP Server = smtp.gmail.com
SMTP port = 465
Connection Security = SSL/TLS
Username = my gmail id
Password = my gmail password
tested the connection too gives me a message that"Connection Test Succeeded! Everything seems properly set up! "
previously this was working perfectly
but now when I send an invoice through mail in odoo its sent without error but the recipient is not receiving the mail
any help will be appreciated
Google made updates to the security measures related to app access, so you will not be able to use password. You need to use App Passwords.
In your Google account: Go to Manage your Google Account and select Security:
Turn on 2-Step Verification.
Once the 2-Step Verification turned on, the app passwords option will be enabled and it will be shown under 2-step verification.
Click on App passwords and create an App password and copy the 16 digits password which you got.
Use that 16 digits instead of the password in the Odoo email configuration settings
You can refer to google help for more details about how to create app passwords.

Getting error like this imap_open(): Couldn't open stream

I am trying to access my company mail id (the mail provider is Gmail) inbox using IMAP. I have applied almost all the possible solutions available here and also on google. But I am facing the same issue.
These are the some solutions which I tried,
allow less secure app access Gmail
enabled IMAP access from Gmail
added novalidate-cert
Here's my code:
$hostname = '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX';
$username = 'mymail#company.ae';
$password = 'mypassword';
// try to connect
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Tiriyo: ' .
imap_last_error());
Error message
Warning: imap_open(): Couldn't open stream {imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX
in \path\to\file\index.php on line 12
I don't see where I'm going wrong. Please help...
Google has deactivated the regular login for third parties on 2022-05-31!
https://support.google.com/accounts/answer/6010255
It is now necessary to implement the Google PHP lib.
https://developers.google.com/gmail/api/quickstart/php
The option for less secure apps has also been removed by Google, which now also eliminates this possibility.
https://myaccount.google.com/lesssecureapps
I ran into the same issue and solved it by generating an app-password for my application.
see: How can I read emails with Google Gmail?

Can send emails through Gmail account only if account has "Access for less secure apps" enabled

If my Gmail account has Access for less secure apps disabled, then my application can't send emails through this account. Instead I get "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required" exception.
Here Google explains that by disabling Access for less secure apps, only apps that use modern security standards can sign in.
What are those modern security standards my code needs to implement and can you show me how to implement them with an example ( not sure if it matters, but my app and Gmail account aren't using 2-step verification )?
Here's the code I'm currently using:
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
var credentialUserName = "myAccount#gmail.com";
var sentFrom = "myAccount#gmail.com";
var pwd = "myPwd";
System.Net.Mail.SmtpClient client =
new System.Net.Mail.SmtpClient("smtp.gmail.com");
client.Port = 587;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential(credentialUserName, pwd);
client.EnableSsl = true;
client.Credentials = credentials;
var mail =
new System.Net.Mail.MailMessage(sentFrom, message.Destination);
mail.Subject = message.Subject;
mail.Body = message.Body;
return client.SendMailAsync(mail);
}
}
Considering that the asp.net-identity-2 tag is applied to this question, and considering that Google requires use of OAuth 2.0 to avoid having to use the Access for less secure applications option, it appears that one option is to use the OWIN middleware able to be found by searching for the term Oauth 2.0 at www.asp.net.
This site hosts an article titled Code! MVC 5 App with Facebook, Twitter, LinkedIn and Google OAuth2 Sign-on that might be of some interest. The article appears to show many screenshots that walk a developer through the process of getting the resource, creating an app, and authenticating with a Google server.
I think it "Less secure" only means that you are giving credentials to third party and they do not use two step verification.
About Google "Less Secure" Settings
It should be noted that Google's statement of Less Secure should not
be read as Insecure. Less Secure Apps is a label describing a
behavioral issue and not a technical issue. Lots of things can go
wrong when you give your credentials to a third party to give to the
authentication authority: the third party might keep the credentials
in storage without telling you, they might use your credentials for
purposes outside the stated scope of the application, they might send
your credentials over a network without encryption, etc. Ultimately,
it is only Less Secure if the third party in question has malicious
intent and therefore you should always be vigilant in knowing who you
are sending your credentials to. COMPanion Corp stores your
credentials only for the purpose of utilizing Googles SMTP Email
service and they are stored using the most up-to-date security.
Source: http://www.goalexandria.com/v7Docs/index.php/Using_Gmail_as_Your_SMTP_Server

Bugzilla Gmail SMTP failed to authenticate

I have a bugzilla 4.4.2 installation. I want to use the gmail smtp service to send email from my application. I have applied these blogs
http://www.dawood.in/bugzilla-alerts-using-gmail/
http://prasadlinuxblog.wordpress.com/2014/02/26/975/
Applied the patches mentioned there. I configured the mta parameters in Bugzilla admin section with my gmail user name and password. Note that, I am not using two step verification in google account. So after all these, the application fails with an Authentication Error. It says the following message
There was an error sending mail from 'myemailaddress#gmail.com' to 'receiver#gmail.com': Could't set FROM: 530 5.5.1 Authentication Required. Learn more at at lib/Email/Send/SMTP/TLS.pm line 49
Cant really figure out whats going wrong here. I found one similar question https://stackoverflow.com/a/8533805/3692283 but I am already following the solution mentioned there.
Check whether the email entered at the SMTP user is still valid. If the password is no longer valid, then it cannot be chosen as the SMTP user name.
The SMTP password is the email's password.

Can't connect to Office Communication Server through Unified Communications API

I am trying to connect to Office Communication Server using the Unified Communications Managed API. I have tried my user and a fresh user enabled for OCS. Both account can successfully log into the Office Communicator client, but fail using the API. When creating the network credential, if I pass in the username in the form domain\username, I get this error:
SupportedAuthenticationProtocols=Ntlm, Kerberos
Realm=SIP Communications Service
FailureReason=InvalidCredentials
ErrorCode=-2146893044
Microsoft.Rtc.Signaling.AuthenticationException: The log on was denied. Check that the proper credentials are being used and the account is active. ---> Microsoft.Rtc.Internal.Sip.AuthException: NegotiateSecurityAssociation failed, error: - 2146893044
If I leave off the domain in the username I this error:
ResponseCode=404 ResponseText=Not Found
DiagnosticInformation=ErrorCode=4005,Source=OCS.mydomain.com,Reason=Destination URI either not enabled for SIP or does not exist
Turns out this was an oversight on my part. Our AD domain and communicator domain are different, I had assumed they were the same.
The network credential is domain\username, and the sip address should have been sip:username#companyname.com, I was using sip:username#domain.com.
Two things to note:
Username should not contain the domain. There should be a separate Domain property of NetworkCredential that you should be using.
You also need to pass in the user URI as well - for example:
//Initialize and register the endpoint, using the credentials of the user the application will be acting as.
UserEndpointSettings userEndpointSettings = new UserEndpointSettings(_userURI, _userServer);
userEndpointSettings.Credential = _credential;
_userEndpoint = new UserEndpoint(_collabPlatform, userEndpointSettings);
_userEndpoint.BeginEstablish(EndEndpointEstablish, _userEndpoint);