PowerShell send SMTP email without (default) authentication - authentication

I am attempting to deliver an email to an Exchange-server using PowerShell. My goal is to use plain old SMTP to deliver a message to a local user (mailbox) on the Exchange-server. The Exchange-server is located within the same network and AD-domain as the sending server and as the logged on sending user.
However the user I am sending from does not have access to send emails on that Exchange-server. And PowerShell seems to send authentication using the logged on user credentials by default.
$smtp = new-object Net.Mail.SmtpClient("exchangeserver.mylan")
$smtp.Send($emailFrom, $emailTo, $subject, $message)
I have tried to add $smtp.UseDefaultCredentials = $false before the $smtp.Send(... line without success.
One solution would be to allow this user to send messages on the Exchange server. However the user will change depending on what service is running this script, so I don't want to solve it that way.
Another solution would be to hardcode credentials using something like $smtp.Credentials = New-Object System.Net.NetworkCredential("DOMAIN\user", "password") (also before $smtp.Send(... line). I've had no luck in this either.
The solution I'd really like is to just send email in PowerShell anonymously using good old auth free SMTP.

1) Create new Receive Connector
2) Enable anonymous authentication on it
3) Lock it down to IP address of the computer you are running the script on

I realize this is old, but I'm surprised there isn't an answer here for this. I was confused initially because I have some similar code I wrote in C# and it works just fine. It seems PowerShell will default to using someone's credentials. I won't assume it's who runs the script, but it could be.
When I'm building up the credential object, I pass in a space for the username and password and that seems to work fine.
$credential = New-Object System.Management.Automation.PSCredential (" ", " ")
If I completely leave out the credential part then it will use someone's credentials or something. Until now I was getting the following message:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated
I hope this helps someone with such an odd problem.

Related

Can't authenticate with SMTP (but IMAP works) Microsoft 365

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

Gmail sending problems

So i try smtplib to send gmail automatically, however it fail because of a error, after some checking, my username and pass are True. So i want to ask if there were any mistakes that can lead to this error.
Here is my code, the port is 465 and i don't want anyone know my pass and my username.
The error message "username and password not accepted" is the standard error message you get from the smtp server when sending the users actual google password.
This method of authentication is not acceptable by the SMTP server after (May 30, 2022). Partially due to the removal of Less secure apps & your Google Account mostly because client login is not considered to be secure.
Your options are to to enable 2fa on our google account and use and create an apps password. Simply use it in place of the password in your code.
smtp.login(username, appsPasswrod)
Or to use XOauth2 and authenticate the application.
Create a sendEmail() function, which will help to send emails to one or more than one recipient by calling the function.
def sendEmail(to, content):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login('youremail#gmail.com', 'your-password')
server.sendmail('youremail#gmail.com', to, content)
server.close()
content = "Message to send"
to = "useremail#gmail.com"
sendEmail(to, content)
NOTE: Do not forget to make sure that the smtplib requires 'enable the less secure apps' feature in your Gmail account. Otherwise, the sendEmail function will not work properly..
Create App Password: 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?

AuthenticationError in reading mail using IMAP protocol using JavaMail

I am trying to read emails from XXX domain using Java Mail API. I am able to login and read the email using IMAPS protocol using PUTTY from server.
However from Java, I am getting Authentication Error:
Following is the screenshot where I am able to connect from PUTTY:
Following is my Code:
Properties properties = new Properties();
properties.put("mail.imap.host", "hostname");
properties.put("mail.imap.port", "993");
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("username", "password");
}
});
Store store = session.getStore("imaps");
store.connect("username", "password");
What does making it stop to read mail from Java ?
Internally, mail domain is using outlook exchange server.
Username being passed is full xxxx#domain.com.
You can remove the property settings; they have no effect since you're using imaps. And you can get rid of the Authenticator since you're passing the username and password explicitly.
You need to pass the host explicitly as well, otherwise it's connecting to localhost, which may be why it's failing. Look at the JavaMail debug output to see what it's actually doing. If that doesn't solve your problem, post the debug output.

Intermittent "Authorization Required" exception when logging into servicem8 API from FileMaker

I have a FileMaker application which pulls Jobs (and clients etc) from servicem8 using the API. As its a private application I just use username/password in the GET_URL. It usually works, but now and then will not login correctly, and I get the message:
- "Authorisation Required"
Restarting FileMaker and/or pasting the URL directly into a browser then trying again seems to resolve the problem.
The only other consistent behaviour seems to be that once it fails once, it will not work again until I restart as above.
Anyone found similar issues or have any ideas?
For Private applications servicem8 uses HTTP Basic Authentication. You can try to reset cached request by calling the same url from FileMaker with a different, but incorrect username and password and then repeating the original request with correct credentials.
servicem8 documentation uses curl for authentication examples and I think this will work better. To implement curl you will need a plugin, like BaseElements or MBS, although on a mac curl could be called through AppleScript.
Try using
BE_Curl_Set_Option ( "CURLOPT_HTTPAUTH" ; 1 )
From This BaseElements help article, we can be sure that Basic clearly isn't the default method:
BE_Curl_Set_Option ( "CURLOPT_HTTPAUTH" ; 1 ) forces Basic auth for
some sites that won't work with the defaults.
ServiceM8 will work consistently with basic auth for private applications as you say, but there are other authentications that will only work when other valid session data is present, which can be misleading when it works at times and not others.