Getting "Client was not authenticated to send anonymous mail during MAIL FROM" error from Exchange SMTP using Rust lettre library - email

I am writing a Rust application that will send email through an Exchange server with SMTP functionality enabled. According to Microsoft's webpage, the settings that are required are:
Server address smtp.office365.com
Port 587
StartTLS Enabled
Credentials for mail account login
These are corroborated by the POP/IMAP settings of the webmail service.
Here is my code (with some censoring):
extern crate lettre;
use self::lettre::email::EmailBuilder;
use self::lettre::transport::smtp::{SecurityLevel, SmtpTransportBuilder, SUBMISSION_PORT};
use self::lettre::transport::smtp::authentication::Mechanism;
use self::lettre::transport::EmailTransport;
pub fn send_mail() {
let email = EmailBuilder::new()
.from("my email")
.to("destination email")
.body("testing")
.subject("testing")
.build()
.unwrap();
// Connect to SMTP server
let mut transport = SmtpTransportBuilder::new(("smtp.office365.com", SUBMISSION_PORT))
.expect("Failed to create email transport")
.encrypt()
.smtp_utf8(true)
.credentials("my email", "my password")
.authentication_mechanism(Mechanism::Login)
.build();
println!("Mail transport built");
println!("{:?}", transport.send(email.clone()));
}
When I compile and run the code,it gives me this error:
Err(Permanent(Response { code: Code { severity:
PermanentNegativeCompletion, category: Unspecified3, detail: 0 },
message: ["5.7.57 SMTP; Client was not authenticated to send anonymous
mail during MAIL FROM [SYXPR01CA0106.ausprd01.prod.outlook.com]"] }))
Why is this happening?
The closest I've come in my research is an issue on GitHub in relation to the lettre library not supporting the Login authentication mechanism (which Office 365 uses); however, the codebase was updated to support Login and I am using the master branch directly from GitHub so theoretically my application should support the Login mechanism.
Edit: Forgot to mention that I attempted an EHLO to the server, but it returned a (Client:(Connection closed)) error.

I used telnet and openssl to try connecting directly to my SMTP server, where I found that AUTH LOGIN requires 3 commands; one to send the AUTH LOGIN code, one to send the username and another to send the password. I found that the lettre library implements all its AUTH commands as single commands, so this wasn't working with the server. I downloaded the source code for the library, changed the send function to do the three separate commands, recompiled my code and everything worked fine :)
My addition to the lettre code:
if (accepted_mechanisms[0] == Mechanism::Login) &&
(accepted_mechanisms.capacity() == 1) {
try_smtp!(self.client.command("AUTH LOGIN"), self);
try_smtp!(self.client.command(base64::encode_config(
&username.as_bytes(),
base64::STANDARD).as_str()), self);
try_smtp!(self.client.command(base64::encode_config(
&password.as_bytes(),
base64::STANDARD).as_str()), self);

Related

KeyCloak fails to send email using SMTP with status 500

I have Keycloak running in a Kubernetes cluster. Authentication works but I need to set up e-mail to be able to send e-mails for verification and password reset.
I have SendGrid set up as an SMTP Relay. These settings (host, port and api key) work when I send mail using the SendGrid java client. However, when pressing Test connection in KeyCloak I get:
[Error] Failed to load resource: the server responded with a status of 500 ()
[Debug] Remove message (services.js, line 14)
[Debug] Added message (services.js, line 15)
[Error] Can't find variable: error
https://<domain>/auth/resources/ong8v/admin/keycloak/js/controllers/realm.js:76 – "Possibly unhandled rejection: {}"
[Debug] Remove message (services.js, line 14)
There isn't much to go on here. I have an e-mail address set up for the currently logged in user. I've also tried resetting the password in case the Test connection functionality was broken but that didn't work either.
The Realm Settings settings user for email are as such:
host: smtp.sendgrid.net
port: 587
from: test#<domain>
Enable StartTLS: true
Username: "apikey"
Password: <api key>
Any idea what can be wrong? Or how to find out? For instance, maybe I can get a more meaningful error message somehow.
Edit:
I got the server logs.
Failed to send email: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.sendgrid.net, 587; timeout 10000;
nested exception is: java.net.SocketTimeoutException: connect timed out
Edit 2:
I've tried sending mail using Telnet using the exact same settings and that works. So apparently it's something with Keycloak or its underlying Java libraries that's causing issues sending e-mail.
Turns out that Keycloak works and that emails were blocked by the hosting provider.

Liferay 7 MailService.sendMail from a custom portlet doesn't work only on HOST SERVER

I have a strange problem with a custom portlet on Liferay 7 to solve:
MailService.sendMail is working from MY COMPUTER with google smtp and a personal account: this means that the code is working...
On my HOST SERVER sending emails with the final-smtp works correctly: I tried both root and liferay user with telnet final-smtp port.
On the Liferay server on HOST SERVER, send e-mails works correctly: if I forget the password, Liferay send me the e-mail.
But ... if I try to send email with my portlet from Liferay on HOST SERVER it doesn't work without any error. I'm using Liferay MailService.sendMail. I post the code but it works (on MY COMPUTER).
I get the service in this way:
#Reference(unbind = "-")
protected void setMailService(MailService mailService) {
_mailService = mailService;
}
And the calling code is in the following:
InternetAddress fromAddress = null;
String newsletterPrefix = null;
InternetAddress toAddress = null;
try {
String smtpUser = PropsUtil.get(
"newsletter.send.mail.smtp.user");
String smtpToUser = PropsUtil.get(
"newsletter.send.mail.smtp.to.user");
if (Validator.isNotNull(smtpUser)) {
fromAddress = new InternetAddress(smtpUser);
}
if (Validator.isNotNull(smtpToUser)) {
toAddress = new InternetAddress(smtpToUser);
}
}
catch (Exception e) {
_log.error(e, e);
result = false;
}
MailMessage mailMessage = new MailMessage(
fromAddress, toAddress, subject, body, true);
mailMessage.setBCC(addressList);
_mailService.sendEmail(mailMessage);
There could be several reasons behind this, some not even code related.
I see you are using this code for a newsletter, which suggests you are using a smtp service that is meant for this.
It could be that your server is in fact sending the email, with success, but the smtp server is simply blocking, rejecting or marking to resend later. Moreover, that server might be configured to not send an error message, or sending an error message in the form of a successful delivery, but the data contains the error.
I would start checking you mail server configuration, and the accounts permissions, then its logs.
Also, you might consider using plugins for mass mail delivery, like this one: https://www.e-systems.tech/blog/-/blogs/connecting-liferay-to-mailgun
Few things you can do to debug this problem:
Make sure you are deploying the intended code on HOST machine. (Silly suggestion, but many times this is the problem.)
Try to set following package's Log level to ALL/DEBUG to see if it shows any problem in logs.com.liferay.mail.service

How can I send emails using my own mail server in Meteor?

I am trying to enable email support for my Meteor application, and since I have my own server I want to also use my own mail server. So I installed postfix in my Debian wheezy server and successfully sent and email to my GMail address, so that means the mail server works properly and sends emails.
When I deploy my Meteor app and try to send an email though, say to do a password reset, my app crashes with the following error:
Exception while invoking method 'forgotPassword' RecipientError: Can't send mail - all recipients were rejected
at Object.Future.wait (/home/loupax/phial/bundle/programs/server/node_modules/fibers/future.js:326:15)
at smtpSend (packages/email/email.js:94)
at Object.Email.send (packages/email/email.js:155)
...
...
My MAIL_URL environment variable is in the format MAIL_URL=smtp://my_domain.tld.
Looks like all I had to do, is change the MAIL_URL environmental variable from smtp://my_domain.tld to smtp://localhost. After that everything worked just fine
Is your server on Amazon? Sometimes SMTP servers are known to block anything sent from certain hosting providers entire IP ranges to block spam.
You might want to consider using a different SMTP server, Amazon's SES, or Mandrill (which has a meteorite package to help) (personally I use both SES and Mandrill).
Note its not only Amazons IP blocks which are in this, its also any hosting provider a spammer can quickly set up. Your SMTP sever probably employs a list from somewhere with all these ips on it
for forgot password email, follow below steps
1) create smtp.js file in server folder and past below code in it
Meteor.startup(function () {
process.env.MAIL_URL =
'smtps://abcd#gmail.com:password#smtp.gmail.com:465';
});
2) paste below code in forgot password.js file
Template.forgot.events({
'click #forgot'(event,template) {
event.preventDefault();
let email = $("#email").val();
// paste below code in server.main.js -> in Meteor.startup function.
/* Accounts.urls.resetPassword = function(token) {
return Meteor.absoluteUrl('reset-password/' + token);
};*/
Accounts.forgotPassword({email:email},function (error,result) {
if(error)
{
alert(error);
}
else
{
console.log(result);
alert("mail sent ..!! Check your mail box");
FlowRouter.go('/login');
}
});
}
});
3 ) in main.js file in server folder paste below code
import '../server/smtp';
Meteor.startup(() => {
// code to run on server at startup
Accounts.urls.resetPassword = function(token) {
return Meteor.absoluteUrl('reset-password/' + token);
};
});
check your mail

Mew gives SMTP error when trying to send through GMail

I'm trying to send an email using the GMail SMTP server.
I have the following setup for mew in emacs:
(default
(mailbox-type 'imap)
(proto "%")
(imap-user my-email)
(imap-server "imap.gmail.com")
(imap-ssl t)
(smtp-server "smtp.gmail.com")
(smtp-auth-list ("PLAIN" "LOGIN" "CRAM-MD5"))
(smtp-user my-email)
(user my-username)
(mail-domain "gmail.com")
(name my-name)
(imap-friend-folder "%from")
(imap-trash-folder "%[Gmail]/All Mail"))
I'm not sure what I'm doing wrong.
The error message is this: 530 5.7.0 Must issue a STARTTLS command first. dr7sm13115113qab.26. This mail has been queued to +queue
What mew configuration settings do I have to change to make this problem go away?
Looks like I forgot to set the variable smtp-ssl to t so that the SMTP connection uses SSL (which GMail requires).

How do you fix 550 must be authenticated sending Mail using Grails?

I'm using Grails Mail plugin and trying to send email and keep getting:
Error 500: Executing action [sendInvite] of controller
[RegisterController] caused exception: Failed messages:
javax.mail.SendFailedException: Invalid Addresses; nested exception
is: com.sun.mail.smtp.SMTPAddressFailedException: 550 must be
authenticated
I'm properly following the instructions at: http://www.grails.org/Mail+plugin
The mail server is returning an error when you try to send out the mail. 550 is a generic SMTP failure code; in this case it looks like you are missing a username and password. Some SMTP servers to not require authentication but most do, especially if they're publicly available on the internet. It's also possible that your SMTP server requires an SSL connection and you're connecting with an unsecured socket.
The example config for gmail shows how to set all the mail server authentication options in Config.groovy:
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "youracount#gmail.com"
password = "yourpassword"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
}
Add "mail.debug": "true" to props to turn on JavaMail debugging to get a better picture of what is happening before the failure.
In my case the 550 error was caused by me having accidentally selected and IMAP account as the default account but sending emails from my Outlook Connector Account (which has no authentication settings to make).
I changed the Outlook Connector Account to default. Resent the emails and no errors.
So check that the correct email account is set up as the default also