How to validate SMTP through yii\swiftmailer\Mailer in Yii? - yii

I wanna validate SMTP credentials used are valid or not before sending an email.
I tried with Yii::$app->mail->SmtpConnect() but it's throwing an error.
How to validate SMTP in Yii?

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

Error 535 - sending SMTP Email to SendGrid using Telnet

I'm trying to send an SMTP Email to SendGrid using Telnet and getting "535 Authentication failed: The provided authorization grant is invalid, expired, or revoked" as a response when I enter my base64 encoded API Key.
I have authenticated my domain.
I have a Full Access SendGrid API Key (and converted it to base64).
I have created and verified a sender (but, it has a mere ...#gmail.com address).
I am following the steps at https://docs.sendgrid.com/for-developers/sending-email/getting-started-smtp.
I have tried port 25 and port 587, but I can't get beyond step 4: Enter your Base64 converted API Key.
What could be causing this error?
Do I need to create a sender with a business email address?
Do I need a paid SendGrid plan?

How to generate tokens for mail verify or forgot password without FusionAuth sending mail?

Until yesterday I was using the default mechanism of sending mails like "verify mail" or "forgot password mail". These mails have specials tokens included inside the mail. Both of these endpoint also returns tokens in the response body.
I am now changing the way of sending mails in my application and I want to do it with a separate service. So to activate my users or change their password I need these tokens, but I dont want FusionAuth to send emails. When disabling "verify mails" or "forgot password", calling these endpoints results in a 403. Is there a way to get this tokens without starting the process of sending a mail by FusionAuth ?
The workaround is to add a fake host to the mail config. But it isn't the best idea since I see then an error in logs when generating tokens.
You can use the /api/user/forgot-password API and set sendForgotPasswordEmail to false.
In the Forgot Password API it is the second example :
Start the forgot password workflow using an API key
This will create you a token and will not send the email. You can then build the link yourself and send the email through an external service.

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.