Using JavaMail to read the mail - java

I am getting this error when tried to read mail using JavaMail. please let me know how to resolve this error. I have added activation.jar and mail.jar into eclipse.
DEBUG POP3: server doesn't support TOP, disabling it
javax.mail.AuthenticationFailedException: Command is not valid in this state.
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:174)
at javax.mail.Service.connect(Service.java:291)
at javax.mail.Service.connect(Service.java:172)
at library.VerifyEmail.main(VerifyEmail.java:40)
Below is the code I am trying:
package library;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import com.sun.mail.pop3.POP3Store;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.SubjectTerm;
import javax.activation.*;
import java.io.*;
public class VerifyEmail {
public static void main(String[] args) throws Exception {
// SUBSTITUTE YOUR ISP's POP3 SERVER HERE!!!
String host = "myhost";
// SUBSTITUTE YOUR USERNAME AND PASSWORD TO ACCESS E-MAIL HERE!!!
String user = "myuser";
String password = "mypass";
// Get a session. Use a blank Properties object.
Session session = Session.getInstance(new Properties());
try {
// Get a Store object
Store store = session.getStore("pop3");
store.connect(host, user, password);
// Get "INBOX"
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.READ_WRITE);
int count = fldr.getMessageCount();
System.out.println(count + " total messages");
// Message numebers start at 1
for(int i = 1; i <= count; i++) {
// Get a message by its sequence number
Message m = fldr.getMessage(i);
// Get some headers
Date date = m.getSentDate();
Address [] from = m.getFrom();
String subj = m.getSubject();
String mimeType = m.getContentType();
System.out.println(date + "\t" + from[0] + "\t" +
subj + "\t" + mimeType);
}
}catch (MessagingException ioex) {
ioex.printStackTrace();
}
}
}

When you're getting the javax.mail.AuthenticationException it means that your application is unable to authenticate to the mail server.
One possible reason for this might be that an SSL certificate of the mail server is missing from the client keystore.

According to microsoft: For exchange 2010, by default, the server would need the client use ssl for pop3.
Without ssl the server responds with "ERR command is not valid in this state."
Here's how to use javamail with ssl - Javamail and Gmail Pop3 SSL

DEBUG POP3: server doesn't support TOP, disabling it
this message can be disable by updating the java mail jar version to 1.4.4

Related

Cannot enroll admin in Hyperledger Fabric using Java Error Caused by: javax.net.ssl.SSLException: Unsupported or unrecognized SSL message

I want to enroll the Admin and store the certificate in the wallet folder. I have initialized the ca server.
# fabric-ca-server init
Next, I have started the ca server successfully.
Now, I want to enroll the admin user using java.
import java.nio.file.Paths;
import java.util.Properties;
import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallets;
import org.hyperledger.fabric.gateway.Identities;
import org.hyperledger.fabric.gateway.Identity;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric.sdk.security.CryptoSuiteFactory;
import org.hyperledger.fabric_ca.sdk.EnrollmentRequest;
import org.hyperledger.fabric_ca.sdk.HFCAClient;
public class EnrollAdmin
{
static
{
System.setProperty("org.hyperledger.fabric.sdk.service_discovery.as_localhost", "true");
}
public static void main(String[] args) throws Exception
{
// Create a CA client for interacting with the CA.
Properties props = new Properties();
props.put("pemFile", "/home/nemo/Fabric2.2-java-master/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem");
props.put("allowAllHostNames", "true");
HFCAClient caClient = HFCAClient.createNewInstance("https://localhost:7054", props);
CryptoSuite cryptoSuite = CryptoSuiteFactory.getDefault().getCryptoSuite();
caClient.setCryptoSuite(cryptoSuite);
// Create a wallet for managing identities
Wallet wallet = Wallets.newFileSystemWallet(Paths.get("wallet"));
// Check to see if we've already enrolled the admin user.
if (wallet.get("admin") != null)
{
System.out.println("An identity for the admin user \"admin\" already exists in the wallet");
return;
}
System.out.println("z1");
// Enroll the admin user, and import the new identity into the wallet.
final EnrollmentRequest enrollmentRequestTLS = new EnrollmentRequest();
enrollmentRequestTLS.addHost("localhost");
enrollmentRequestTLS.setProfile("tls");
Enrollment enrollment = caClient.enroll("admin", "adminpw", enrollmentRequestTLS); /*problem*/
System.out.println("z2");
Identity user = Identities.newX509Identity("Org1MSP", enrollment);
wallet.put("admin", user);
System.out.println("Successfully enrolled user \"admin\" and imported it into the wallet");
}
}
But this error message is showing.
Exception in thread "main" org.hyperledger.fabric_ca.sdk.exception.EnrollmentException: Url:https://localhost:7054, Failed to enroll user admin
at org.hyperledger.fabric_ca.sdk.HFCAClient.enroll(HFCAClient.java:518)
at fabricjavaclient.EnrollAdmin.main(EnrollAdmin.java:49)
Caused by: javax.net.ssl.SSLException: Unsupported or unrecognized SSL message
at java.base/sun.security.ssl.SSLSocketInputRecord.handleUnknownRecord(SSLSocketInputRecord.java:451)
at java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:175)
Please help me to solve this problem.

javax.mail.AuthenticationFailedException: [AUTH] Web login required

I build an application using Java to read emails. And It worked without any errors past days. But suddenly today came up an error like this.
javax.mail.AuthenticationFailedException: [AUTH] Web login required: https://support.google.com/mail/answer/78754
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:207)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at MailReader.readMail(MailReader.java:44)
at MailReader.run(MailReader.java:32)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
I can't figure out how to fix this. I didn't put 2-way authentication. And also I put less secure app allowed. So I can't figure out what is wrong. Anybody can help me? I greatly appreciate that.
Here is the code I am using,
String host = "pop.gmail.com";
String username = "somename#gmail.com";
String password = "password";
Properties prop = new Properties();
Session session = Session.getInstance(prop, null);
Store store = session.getStore("pop3s");
store.connect(host, username, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
The error was due to an error at Google, which caused POP3 services to work incorrectly. It was fixed after 2 days.
Could not find official statement, only forum posts. Related sources:
1, 2, 3
My working snippet looks like below:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class CheckingMails {
public static void check(String host, String user, String password)
{
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.pop3s.host", host);
properties.put("mail.pop3s.port", "995");
properties.put("mail.pop3s.starttls.enable", "true");
// Setup authentication, get session
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
// session.setDebug(true);
// create the POP3 store object and connect with the pop server
Store store = session.getStore("pop3s");
store.connect();
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
// close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";
String username = "abc#gmail.com";// change accordingly
String password = "*****";// change accordingly
check(host, username, password);
}
}
My problem was that the same code was working on local but not on the remote cloud (Bitbucket pipeline) although I set the less secure enable. I solved it by enabled 2 step verification and create an app password. Then used this app password instead of the normal password in the code.
You can check the following link as well: https://docs.maildev.com/article/121-gmail-web-login-required-error---answer78754-failure

Java IMAP endless loop while writing to EML

We got a serious problem in our system which is processing mails from IMAP and saving it as EML. Thing is, everything works in production but not on dev machine anymore, therefore we cannot make any fixes or further development. This is kind of strange, because also this example does not work:
package com.test;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
public class ReadMail {
public static void main(String args[]) throws Exception {
String host = "mail";
String user = "xxx";
String password = "zzz";
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("imap");
store.connect(host, user, password);
Folder folder = store.getFolder("a");
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println(message[i].getSentDate());
System.out.println(message[i].getFrom()[0]);
System.out.println(message[i].getSubject());
try (OutputStream out = new FileOutputStream("something"+i+".eml")) { // fix the name of course
message[i].writeTo(out);
}
}
folder.close(true);
store.close();
}
}
In writeTo it makes endless loop and creates file which grows until the disk is full. This is from com.sun.mail.imap.IMAPMessage
/**
* Write out the bytes into the given OutputStream.
*/
public void writeTo(OutputStream os)
throws IOException, MessagingException {
if (bodyLoaded) {
super.writeTo(os);
return;
}
InputStream is = getMimeStream();
try {
// write out the bytes
byte[] bytes = new byte[16*1024];
int count;
while ((count = is.read(bytes)) != -1)
os.write(bytes, 0, count);
} finally {
is.close();
}
}
It will never exit from the while clause. Should it be some error on the Postfix side? The mail is multipart MIME message and the EML created are just multiple copies of EML. Only difference between prod and dev machine is HW. JDK8 is the same. Any hints?
Java mail API used:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.6</version>
</dependency>
UPDATE SOLVED: ESET Nod32 Antivirus software intercept the IMAP traffic in that way, that the buffer never returns -1! After disabling ESET Mail, everything works.

Secure FTP From ColdFusion 9 Using Java FTP Client

This is a followup of this question. The correct answer leads to an attempt to use the SFTPClient class in the Apache Commons library.
I can connect. The next step is to upload a file. There is a lot of reference material with sample source code. I used this one as my guide. It's not secure FTP, but it's simple to follow. This is the java code I was attempting to emulate:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FTPUploadFileDemo {
public static void main(String[] args) {
String server = "www.myserver.com";
int port = 21;
String user = "user";
String pass = "pass";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// This was considered unnecessary because I was sending n ASCII file
// APPROACH #1: uploads first file using an InputStream
File firstLocalFile = new File("D:/Test/Projects.zip");
String firstRemoteFile = "Projects.zip";
InputStream inputStream = new FileInputStream(firstLocalFile);
System.out.println("Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
and some more code that's not relevent,
This is my ColdFusion equivalent:
localFilename = "d:\dw\dwtest\dan\textfiles\randomText.txt";
remoteFileName = "randomText.txt";
javaFtpClient = CreateObject("java",
"org.apache.commons.net.ftp.FTPSClient").init("SSL", JavaCast("boolean",true));
// note that I am using a secure client
javaInputFile = createObject("java", "java.io.File").init(localFilename);
javaInputStream = createObject("java", "java.io.FileInputStream").init(javaInputFile);
// connect and login
javaFtpClient.connect(JavaCast("string","something"),990);
loginStatus = javaFtpClient.login('valid username','valid password');
writeoutput("login status " & loginStatus & "<br>");
javaFtpClient.enterLocalPassiveMode();
uploadStatus = javaFtpClient.storeFile(remoteFileName, javaInputStream);
writeOutput("upload status " & uploadStatus & "<br>"); javaInputStream.close();
// logout and disconnect
javaFtpClient.logout();
javaFtpClient.disconnect();
writeoutput("done" & "<br>");
The output shows a successful login and an unsuccessful file upload. The lack of file was confirmed using FileZilla.
Can anybody see why the file was not uploaded?
The command javaFtpClient.execProt("P") is required. Setting PROT to "P" sets the Data Channel Protection Level to private.

Need help about "Get Attachment File Name" Tutorial from Java2s.com

i try the tutorial Get Attachment File Name from Java2s.com.
What i'm doing is to read email from the Outlook Web Access Light.
If i put the url address of the Outlook Web Access Light, i have the error:
Exception in thread "main" javax.mail.NoSuchProviderException: No provider for http
at javax.mail.Session.getProvider(Session.java:455)
at javax.mail.Session.getStore(Session.java:530)
at javax.mail.Session.getFolder(Session.java:602)
at MainClass.main(MainClass.java:19)
Java Result: 1
I don't understand the line :
("protocol://username#host/foldername");
here is the code:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
public class MainClass {
public static void main(String[] args) throws Exception {
URLName server = new URLName("protocol://username#host/foldername");
Session session = Session.getDefaultInstance(new Properties(), new MailAuthenticator());
Folder folder = session.getFolder(server);
if (folder == null) {
System.out.println("Folder " + server.getFile() + " not found.");
System.exit(1);
}
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println(messages[i].getSize() + " bytes long.");
System.out.println(messages[i].getLineCount() + " lines.");
String disposition = messages[i].getDisposition();
if (disposition == null){
; // do nothing
}else if (disposition.equals(Part.INLINE)) {
System.out.println("This part should be displayed inline");
} else if (disposition.equals(Part.ATTACHMENT)) {
System.out.println("This part is an attachment");
String fileName = messages[i].getFileName();
System.out.println("The file name of this attachment is " + fileName);
}
String description = messages[i].getDescription();
if (description != null) {
System.out.println("The description of this message is " + description);
}
}
folder.close(false);
}
}
class MailAuthenticator extends Authenticator {
public MailAuthenticator() {
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
}
Thank you for your support
have a nice day
Given the error message I really think javaMail is expecting for protocol one of "smtp:" or "imap:" or "pop3:", because it is the way it constructs its session.
I don't think it will ever work with a web access, you have to get the address of the pop3/imp/smtp server the web interface connects to.
I'm not sure but "protocol://username#host/foldername" seems to describe a format rather than a real url, i.e. it tells you to add a protocol, a user name, a host and a folder like "http://Thomas#stackoverflow.com/need-help-about-get-attachment-file-name-tutorial-from-java2s-com" (just an example of how it might look like, this particular url is not likely to work/exist/whatever :) ).

Categories

Resources