JavaMail through Exchange server with SSO Authentication - java

I've seen several posts that offer a solution to something very similar to my situation but for whatever reason it does not work for me.
For example, here it's presented as a working sample illustrating OP's related problem and here as an actual answer.
I need to send e-mail as myself from my Exchange account via SMTP using SSO UserID and Password. This all happens in a restricted corporate environment.
From what I understand from the debug info I'm successfully connecting to an SMTP server and then fail user authentication with 530 5.7.1 Client was not authenticated. NTLM authentication itself seems to be enabled.
DEBUG:
DEBUG: setDebug: JavaMail version 1.5.4
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "server.bank.com", port 25, isSSL false
220 server1.corp.bank.com Microsoft ESMTP MAIL Service ready at Mon, 24 Aug 2015 17:15:24 -0400
DEBUG SMTP: connected to host "server.bank.com", port: 25
EHLO server2.corp.bank.com
250-server1.corp.bank.com Hello [xxx.xxx.xxx.xxx]
250-SIZE
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-X-ANONYMOUSTLS
250-AUTH NTLM LOGIN
250-X-EXPS GSSAPI NTLM
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250-XEXCH50
250-XRDST
250 XSHADOW
DEBUG SMTP: Found extension "SIZE", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "X-ANONYMOUSTLS", arg ""
DEBUG SMTP: Found extension "AUTH", arg "NTLM LOGIN"
DEBUG SMTP: Found extension "X-EXPS", arg "GSSAPI NTLM"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "XEXCH50", arg ""
DEBUG SMTP: Found extension "XRDST", arg ""
DEBUG SMTP: Found extension "XSHADOW", arg ""
DEBUG SMTP: use8bit false
MAIL FROM:<first.last#bank.com>
530 5.7.1 Client was not authenticated
DEBUG SMTP: got response code 530, with response: 530 5.7.1 Client was not authenticated
Essential part of my code:
static void sendEmail(){
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.port", "25");
// props.setProperty("mail.debug", "true");
// props.setProperty("mail.debug.auth", "true");
props.setProperty("mail.smtp.starttls.enable","true");
props.setProperty("mail.smtp.auth.mechanisms", "NTLM");
props.setProperty("mail.smtp.auth.ntlm.domain", user_sso_domain);
// Session session = Session.getDefaultInstance(props);
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user_sso_id, user_sso_password);
}
});
session.setDebug(true);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(email_from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(email_to));
message.setSubject("Test Message");
message.setText("This is my test message");
Transport.send(message);
} catch (Exception ex) {
ex.printStackTrace();
}
}
I would appreciate your suggestions for further troubleshooting.
EDIT
Working code after implementing the fix and better practices from the accepted answer:
private static void sendEmail(){
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.port", "25");
// props.setProperty("mail.debug", "true");
// props.setProperty("mail.debug.auth", "true");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable","true");
props.setProperty("mail.smtp.auth.mechanisms", "NTLM");
props.setProperty("mail.smtp.auth.ntlm.domain", user_sso_domain);
Session session = Session.getInstance(props);
session.setDebug(true);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(email_from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(email_to));
message.setSubject("Test Message");
message.setText("This is my test message");
Transport.send(message, user_sso_id, user_sso_password);
} catch (Exception ex) {
ex.printStackTrace();
}
}

You need to set "mail.smtp.auth" to "true".
Or, better yet, fix these common mistakes and make your program much simpler.

Related

SubEthaSMTP Unexpected error in the SMTP handler thread NoClassDefFoundError jakarta/mail/internet/AddressException

SubEthaSMTP server running fine on port 25001. After a successful authentication from my client code to Subethasmtp server i am having this error message org.subethamail.smtp.server.Session: Unexpected error in the SMTP handler thread
java.lang.NoClassDefFoundError: jakarta/mail/internet/AddressException
This is my SMTPServerConfig class
#Configuration
public class SMTPServerConfig {
private final SMTPServer smtpServer;
private final SimpleMessageListener marketingMsgListener;
private final UsernamePasswordValidator authValidator;
private final EasyAuthenticationHandlerFactory easyAuth;
public SMTPServerConfig(SimpleMessageListener marketingMsgListener) {
authValidator = new SimpleAuthValidatorImpl();
easyAuth = new EasyAuthenticationHandlerFactory(authValidator);
this.marketingMsgListener = marketingMsgListener;
this.smtpServer = SMTPServer
.port(25001)
.simpleMessageListener(this.marketingMsgListener)
.requireAuth(true)
.authenticationHandlerFactory(easyAuth)
.hostName("localhost")
.hideTLS(false)
.enableTLS(true)
.requireTLS(false)
.requireAuth(true)
.connectionTimeout(1, TimeUnit.MINUTES)
.maxMessageSize(10000)
.maxConnections(20)
.build();
this.smtpServer.stop();
this.smtpServer.start();
}
I am using usernamepasswordvalidator
#Configuration
public class SimpleAuthValidatorImpl implements UsernamePasswordValidator {
private final String CREDENTIALS_LOGIN = "christclau";
private final String CREDENTIALS_PASSWORD = "password";
#Override
public void login(String username, String password, MessageContext context) throws LoginFailedException {
if(CREDENTIALS_LOGIN.equals(username) && CREDENTIALS_PASSWORD.equals(password)){
System.out.println("yes Authenticated successfully");
}else{
System.err.println("no Invalid authentication !");
throw new LoginFailedException();
}
}
}
This is my mail client to send message to the server
public void sendMail(Mail mail) {
final String username = "christclau";
final String password = "password";
Properties prop = new Properties();
prop.put("mail.smtp.host", "localhost");
prop.put("mail.smtp.port", "25001");
prop.put("mail.smtp.auth", "true");
//prop.put("mail.debug", "true");
//prop.put("mail.smtp.starttls.enable", "true"); //TLS
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(mail.getFrom()));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(mail.getTo())
);
message.setSubject(mail.getSubject());
message.setText("HI you have done sending mail with outlook");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
This is the output message
DEBUG: setDebug: Jakarta Mail version 1.6.7
DEBUG: getProvider() returningjavax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: need username and password for authentication
DEBUG SMTP: protocolConnect returning false, host=localhost, user=MY PC, password=<null>
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "localhost", port 25001, isSSL false 220 localhost ESMTP SubEthaSMTP null
DEBUG SMTP: connected to host "localhost", port: 25001
EHLO DESKTOP-FFJA5IP
250-localhost
250-8BITMIME
250-SIZE 10000
250-STARTTLS
250-CHUNKING
250-AUTH PLAIN LOGIN
250 Ok
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "SIZE", arg "10000"
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN"
DEBUG SMTP: Found extension "Ok", arg ""
DEBUG SMTP: protocolConnect login, host=localhost, user=christclau, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM XOAUTH2
DEBUG SMTP: Using mechanism LOGIN
DEBUG SMTP: AUTH LOGIN command trace suppressed
yes Authenticated successfully
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<christoozu#gmail.com>
2022-02-26 11:21:40.081 ERROR 9452 --- [127.0.0.1:50466] org.subethamail.smtp.server.Session : Unexpected error in the SMTP handler thread
java.lang.NoClassDefFoundError: jakarta/mail/internet/AddressException
at org.subethamail.smtp.internal.command.MailCommand.execute(MailCommand.java:74) ~[subethasmtp-6.0.1.jar:na]
at org.subethamail.smtp.internal.server.RequireTLSCommandWrapper.execute(RequireTLSCommandWrapper.java:32) ~[subethasmtp-6.0.1.jar:na]
at org.subethamail.smtp.internal.server.RequireAuthCommandWrapper.execute(RequireAuthCommandWrapper.java:35) ~[subethasmtp-6.0.1.jar:na]
at org.subethamail.smtp.internal.server.CommandHandler.handleCommand(CommandHandler.java:86) ~[subethasmtp-6.0.1.jar:na]
at org.subethamail.smtp.server.Session.runCommandLoop(Session.java:261) ~[subethasmtp-6.0.1.jar:na]
at org.subethamail.smtp.server.Session.run(Session.java:170) ~[subethasmtp-6.0.1.jar:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
Caused by: java.lang.ClassNotFoundException: jakarta.mail.internet.AddressException
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) ~[na:na]
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520) ~[na:na]
... 9 common frames omitted
This is my dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.github.davidmoten</groupId>
<artifactId>subethasmtp</artifactId>
<version>6.0.1</version>
</dependency>
Spring Boot 2.6 and earlier still use the javax.mail namespace for JakartaMail (formerly JavaMail), while your SubEtha SMTP version seems to expect the jakarta.mail namespace. Spring Boot explicitly specifies versions of the JakartaMail package, see Spring Boot Dependency Versions and search for jakarta.mail. For Spring Boot 2.6.4, it lists version 1.6.7, and that version is still based on the javax.mail namespace.
You need to downgrade SubEtha SMTP to a version that still uses the javax.mail namespace of JakartaMail/JavaMail, and wait for Spring Boot 3 before using a version that needs the jakarta.mail namespace.
In theory, you can also set the Maven property jakarta-mail.version to 2.0.1, but this could cause problems in other parts of Spring Boot, so I do not recommend that.

JavaMail - Delay notification in SMTP - office 365

I am using the JavaMail to connect and verify the username and password in office 365.
I use the following java code to check the connectivity,
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
props.put("mail.smtp.host", "smtp.office365.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.auth", true);
System.out.println("Before Session... #################################################");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username_xxxx#xxx.com", "password_xxxxx");
}
});
System.out.println("After Session... #################################################");
session.setDebug(true);
Transport transport = session.getTransport("smtp");
System.out.println("Before Connection... #################################################");
transport.connect();
System.out.println("After Connection... #################################################.");
if(transport.isConnected()) {
System.out.println("Connected Successfully : " + transport);
System.out.println("#################################################");
} else {
System.out.println("Not Connected : " + transport);
}
transport.close();
Mostly 70% of the time, transport.connect() works as expected where the greeting message (220) is received in less than 100ms but there are sometimes (say after 3 hours of the application is deployed in webserver), transport.connect() takes more than 2 minutes to send the greetings message
2020-08-23 11:38:16,930 ERROR [stderr] (default task-415) Before transport connection ::: Sun Aug 23 11:38:16 UTC 2020
2020-08-23 11:38:16,931 INFO [stdout] (default task-415) DEBUG SMTP: useEhlo true, useAuth true
2020-08-23 11:38:16,933 INFO [stdout] (default task-415) DEBUG SMTP: trying to connect to host "smtp.office365.com", port 587, isSSL false
2020-08-23 11:40:27,657 INFO [stdout] (default task-415) 220 BL0PR02CA0082.outlook.office365.com Microsoft ESMTP MAIL Service ready at Sun, 23 Aug 2020 11:40:27 +0000
I enabled the session logs and we could see the 11:40:27,657 log (220 BL0PR02CA0082.outlook.office365.com Microsoft ESMTP MAIL Service ready) takes a long time to receive.
I did some surfing and found the root cause is due to the SMTP server https://www.rfc-editor.org/rfc/rfc5321#section-4.5.3.2.1 where the greetings message 220 can be send in delay!
How can we avoid this delay is my question ?
Anyhelp is appreciated!
Thanks,
Harry

Cannot read emails office365 using javaMail & IMAPS

I'm facing an error using javaMail & IMAPS to read emails on email account of my company hosted in office 365.
I'm using this test class:
public class TestMail {
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties props = System.getProperties();
props.put("mail.imaps.auth.plain.disable","true");
props.setProperty("mail.imaps.timeout", "100000");
props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.ssl.enable", "true");
try {
Session session = Session.getInstance(props, null);
session.setDebug(true);
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "my-name#mycompagny.com", "MY_PASSWORD");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
}
I'm getting the following error:
DEBUG: setDebug: JavaMail version 1.4.7
DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle]
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: disable AUTH=PLAIN
DEBUG IMAPS: trying to connect to host "outlook.office365.com", port 993, isSSL true
* OK The Microsoft Exchange IMAP4 service is ready. [UABSADIAUAAyADYANABDAEEAMAAwADAANAAuAEYAUgBBAFAAMgA2ADQALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=outlook.office365.com, user=my-name#mycompagny.com, password=<non-null>
DEBUG IMAPS: LOGIN command trace suppressed
DEBUG IMAPS: LOGIN command result: A1 NO LOGIN failed.
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:661)
at javax.mail.Service.connect(Service.java:295)
at com.afklm.bagdss.task.TestMail.main(TestMail.java:25)

java mail logs html template to catalina.out

I am using velocity to generate HTML template based content for the email which is to be sent, and Java Mail API with Spring's MimeMessageHelper to send emails. The problem i am facing is that while rendering, HTML template is thrown to catalina.out which is making the file grow in size and that is not desirable.
I have a separate application log file where the logs are generated. Is there any way so that I can redirect this rendering to my application log file? Or may be I can stop this to be thrown at catalina.out.
Below is the details which gets written while sending email
Loading javamail.default.providers from jar:file:/D:/workspace/EmailService/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/email-service/WEB-INF/lib/mail-1.4.jar!/META-INF/javamail.default.providers
DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type#2025b64d; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.nagarro.com", port 587, isSSL false
220 fuseout2c MailAnyone extSMTP Tue, 23 Jul 2013 02:37:58 -0700
DEBUG SMTP: connected to host "smtp.nagarro.com", port: 587
EHLO Vaibhav202001
250-fuseout2c Hello Vaibhav202001 [14.141.12.161]
250-SIZE 52428800
250-PIPELINING
250-AUTH LOGIN
250-STARTTLS
250 HELP
DEBUG SMTP: Found extension "SIZE", arg "52428800"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN"
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
STARTTLS
220 TLS go ahead
EHLO Vaibhav202001
250-fuseout2c Hello Vaibhav202001 [14.141.12.161]
250-SIZE 52428800
250-PIPELINING
250-AUTH LOGIN
250 HELP
DEBUG SMTP: Found extension "SIZE", arg "52428800"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN"
DEBUG SMTP: Found extension "HELP", arg ""
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
334 VXNlcm5hbWU6
anNhZy5zdXBwb3J0QG5hZ2Fycm8uY29t
334 UGFzc3dvcmQ6
SnNhZ0AxMjM0
235 Authentication succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<jsagteam#nagarro.com>
250 OK
RCPT TO:<vaibhav.shukla#nagarro.com>
250 Accepted
DEBUG SMTP: Verified Addresses
DEBUG SMTP: vaibhav.shukla#nagarro.com
DATA
354 Enter message, ending with "." on a line by itself
Date: Fri, 26 Jul 2013 12:00:48 +0530 (IST)
From: JSAG Team <jsagteam#nagarro.com>
To: vaibhav.shukla#nagarro.com
Message-ID: <1817391686.01374820248531.JavaMail.vaibhav2020#Vaibhav202001>
Subject: JSAG Home page - subscribers list
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_Part_0_999692932.1374820244866"
------=_Part_0_999692932.1374820244866
Content-Type: multipart/related;
boundary="----=_Part_1_1241615899.1374820244889"
------=_Part_1_1241615899.1374820244889
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit
//My Email Template goes here
------=_Part_1_1241615899.1374820244889--
------=_Part_0_999692932.1374820244866--
250 OK id=1V1Z2g-0002Rh-HO
QUIT
221 fuseout2c closing connection
And here is the logging configuration
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${catalina.home}/logs/email-service.log
log4j.appender.file.MaxFileSize=1000KB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-4p %m%n
log4j.appender.DatePattern='.'yyyy-MM-dd
# Root logger option
log4j.rootLogger=WARN, file
log4j.logger.com.nagarro=WARN
Also the code to send email
JavaMailSender mailSender; // injected through Spring DI
/**
* The mail message.
*/
SimpleMailMessage mailMessage; // Spring DI
#Override
public void sendEMail(final EmailServiceRequest request, byte[] data) {
MimeMessage message = mailSender.createMimeMessage();
OutputStream outStream = null;
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// set attributes
if (null != request.getRecipientEmailId()) {
helper.setTo(request.getRecipientEmailId());
}
helper.setFrom(request.getSenderEmailId());
helper.setSubject(request.getSubject());
helper.setText(request.getContent(), true);
// check for recipient list
if (null != request.getRecipients() && !request.getRecipients().isEmpty()) {
InternetAddress[] recipients = new InternetAddress[request.getRecipients().size()];
for (int index = 0; index < request.getRecipients().size(); index++) {
recipients[index] = new InternetAddress(request.getRecipients().get(index));
}
helper.setTo(recipients);
}
// data handler
if (null != data) {
try {
File file = File.createTempFile(request.getAttachmentName(), "");
outStream = new FileOutputStream(file);
outStream.write(data);
helper.addAttachment(request.getAttachmentName(), file);
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
if (!StringUtil.isNullOrEmpty(request.getEmailIdCC())) {
helper.addCc(request.getEmailIdCC());
}
if (!StringUtil.isNullOrEmpty(request.getEmailIdBCC())) {
helper.addBcc(request.getEmailIdBCC());
}
mailSender.send(message);
} catch (MessagingException e) {
logger.error(e.getLocalizedMessage(), e);
}
}
I assume you have defined a bean with class org.springframework.mail.javamail.JavaMailSenderImpl in your context configuration.
If so, you could try to set the debug property on the session.
mailSender.getSession().setDebug(false);
Or create a properties file and set set the value there.
mail.debug=false

Authentication Error with Java Mail

I'm using the Java Mail API for the first time and I can't get things working. My server requires authentication, so I'm having to use that. I keep getting the following error:
> 250-PIPELINING 250-SIZE 40960000
> 250-ETRN 250-STARTTLS 250-AUTH PLAIN
> LOGIN 250-AUTH=PLAIN LOGIN
> 250-ENHANCEDSTATUSCODES 250 8BITMIME
> DEBUG SMTP: Found extension
> "PIPELINING", arg "" DEBUG SMTP: Found
> extension "SIZE", arg "40960000" DEBUG
> SMTP: Found extension "ETRN", arg ""
> DEBUG SMTP: Found extension
> "STARTTLS", arg "" DEBUG SMTP: Found
> extension "AUTH", arg "PLAIN LOGIN"
> DEBUG SMTP: Found extension
> "AUTH=PLAIN", arg "LOGIN" DEBUG SMTP:
> Found extension "ENHANCEDSTATUSCODES",
> arg "" DEBUG SMTP: Found extension
> "8BITMIME", arg "" DEBUG SMTP: Attempt
> to authenticate DEBUG SMTP: check
> mechanisms: LOGIN PLAIN AUTH LOGIN 334
> Base64text base64text 334 base64text
> base64text 235 2.7.0 Authentication
> successful DEBUG: getProvider()
> returning
> javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun
> Microsystems, Inc] DEBUG SMTP: useEhlo
> true, useAuth true
> javax.mail.AuthenticationFailedException:
> failed to connect, no password
> specified?
> at javax.mail.Service.connect(Service.java:329)
> at javax.mail.Service.connect(Service.java:176)
> at javax.mail.Service.connect(Service.java:125)
> at javax.mail.Transport.send0(Transport.java:194)
> at javax.mail.Transport.send(Transport.java:124)
> at Mailman.main(Mailman.java:61)
As you can see, I'm getting an "Authentication successful" message, but then it kicks me out on an "AuthenticationFailedException." I'm stumped...
Here's the relevant part of the source:
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "25");
properties.setProperty("mail.smtp.user", "myemailhere");
properties.setProperty("mail.smtp.password", "mypasshere");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.debug", "true");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
Transport transport = session.getTransport("smtp");
transport.connect(host, 25, "myemailhere", "mypasshere");
message.saveChanges();
Transport.send(message);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
Any suggestions would be GREATLY appreciated...
I changed it to
message.setText("This is actual message");
Transport transport = session.getTransport("smtp");
transport.connect( null,smtpUser,smtpPassword); //host, 25, "myemailhere", "mypasshere");
message.saveChanges();
transport.sendMessage(message,message.getAllRecipients());
// Transport.send(message);
// Send message
// Transport.send(message);
System.out.println("Sent message successfully....");
and it worked

Categories