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
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
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?
I recently encountered a SwiftMail error while trying to send a mail through gmail.
Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted.
I was trying to send mail through my gmail and google thought that I was a spam(maybe because I was requesting too fast) I received a mail from them saying my account was access and I told them it was me. I was able to send mail without problem and it just occured now.
This is the contents of my env file.
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=talentscoutphil#gmail.com
MAIL_PASSWORD=mypasswordhere
MAIL_FROM=talentscoutphil#gmail.com
MAIL_NAME=talentscout
I researched on the internet and some answers includes enabling the "access for lesser app" and "unlocking gmail captcha" which sadly didn't work for me until I found the 2-step verification.
What I did the following was:
enable the 2-step verification to google HERE
Create App Password to be use by your system HERE
I selected Others (custom name) and clicked generate
Went to my env file in laravel and edited this
MAIL_USERNAME=talentscoutphil#gmail.com
MAIL_PASSWORD=thepasswordgenerated
Restarted my apache server and boom! It works again.
This was my solution. I created this to atleast make other people not go wasting their time researching for a possible answer.
I had the same problem, changing my gmail password fixed the issue, and also don't forget to enable less secure app on on your gmail account
i had same issue i resolve this use under
go to gmail.com
my account
and enable
Allow less secure apps: ON
it start works
I had everything fine. Less secure app option was also enabled. Still, I was getting the error. What I have done is:
Google will send you Critical security alert
Then you have to authorize that activity. ( Clicking on 'YES, THAT WAS ME' type thing )
Then you can try sending email again.
From May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.
Important: This deadline does not apply to Google Workspace or Google Cloud Identity customers. The enforcement date for these customers will be announced on the Workspace blog at a later date.
For more information, continue to read.
https://support.google.com/accounts/answer/6010255?hl=en&visit_id=637919157823422324-2612210762&p=less-secure-apps&rd=1
This is my .env mail settings
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
MAIL_USERNAME=example#gmail.com
MAIL_PASSWORD=hello27
MAIL_ENCRYPTION=tls
i was getting thesame error as stated in the question but by using
php artisan config:cache
Everything worked fine
Gmail tends to block usage of mailing addresses which are being used in other applications as username for security reasons. Either you should create a new email address for mail purpose or you must go to the Less Secure App Access and turn on the access for less secure apps. Gmail will send you a mail for confirmation from where you can verify that those changes were made by yourself. Only then, you can use such mailing addresses for mailing purpose through applications.
There is no need to update anything in config/mail.php. just put you credential in .env with this specific key's. This is my .env file.
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=example#gmail.com
MAIL_PASSWORD=********
MAIL_ENCRYPTION=tls
I had the same issue after long time debugging and googling i have found the solution. that by enabling less secure apps. the email started working.
if your gmail is secure with 2 step verification you can't enable less secure app. so turn off 2 step verification and enable less secure app. by click here enable less secure apps on your gmail account
This single step worked for me... No 2-step verification.
As I had created a dummy account for my local development, so I was OK with this setting.
Make sure you only do this if your account contains NO personal or any critical data.
This is just another way of tackling this error and NOT secure.
I turned ON the setting to alow less secured apps to be allowed access.
Form here :
https://myaccount.google.com/lesssecureapps
I had the same problem, then I did this two steps:
Enable "Allow less secure apps" on your google account security policy.
Restart your local servers.
I encountered the same issue and solved it with no 2FA enabled ("Allow less secure apps" is still in need).
After checking Google error code list, I thought maybe there are some errors in .env.
Below settings are tested in Laravel 8 and worked:
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=username#gmail.com
MAIL_PASSWORD='your#password_here' # put the password in quotes
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=username#gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Please remember that put the password in quotes. That works for me.
If your using your cpanel custom email, change your host from smtp.gmail.com to your domain name. it worked for me
As from May 30, 2022 Google has stopped the support of third-party apps or devices which ask you to signin to your Google Account using only your username and password.
To solve this,
make sure you that you have enabled 2-step verification.
Then select App paswords.
select app and device you want to generate the app password for.
on select app select mail then on device choose and name a custom device.
After that, a password will be generated for you to use. Replace your original password with the generated password. Refresh or upload your files to the server the reload.
It will work
I had this issue. first checked the credentials and username, they were all good, then restarted my server (docker stop/start) and it works now. something with cache I believe
In my cPanel account few e-mail accounts are working properly, but some of the email account does not receive or send mails.
here are the errors that I got:
when sending from a gmail account to the cPanel mail:
SMTP error from remote mail server after end of data:
550 High probability of spam
When trying to send from the cPanel email account to my gmail account I get the following message:
Could not deliver message, address not found or don't receive messages.
Can anyone help me solve this?
There are many reasons why this error could occur.
Before that I would recommend that you turn on your Email accounts' Authentication (both SPF and DKIM), those are done through:
cPanel -> Authentication (under the Email section) -> Turn Off DKIM and SPF, then turn them back On
About the second issue - I believe that your domain's mail exchanger (a setting in cPanel) is not properly configured.
If you wish to receive emails for a domain in your cPanel account you need to the following:
cPanel -> Mail Exchanger -> Select your domain -> Select Local Mail Exchanger
You should also see if your mailbox is not Suspended or Partially Suspended