Using this code:
import java.io.*;
import java.util.*;
import javax.mail.*;
public class Mbox {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("mail.store.protocol", "mstor");
properties.setProperty("mstor.mbox.metadataStrategy", "none");
properties.setProperty("mstor.mbox.cacheBuffers", "disabled");
properties.setProperty("mstor.cache.disabled", "true");
properties.setProperty("mstor.mbox.bufferStrategy", "mapped");
properties.setProperty("mstor.metadata", "disabled");
Session session = Session.getDefaultInstance(properties);
try {
Store store = session.getStore(new URLName("mstor:C:/INBOX"));
store.connect();
Folder inbox = store.getDefaultFolder().getFolder("inbox");
inbox.open(Folder.READ_ONLY);
Message m = inbox.getMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to setup an mbox reading program in java. I have tried both on Linux and Windows but every time I get the exception javax.mail.NoSuchProviderException: No provider for mstor on session.getStore("mstor:C:/INBOX"). I searched for a while and made the properties file as shown above but still the error persited.
javax.mail.NoSuchProviderException: No provider for mstor
at javax.mail.Session.getProvider(Session.java:473)
at javax.mail.Session.getStore(Session.java:547)
at Mbox.main(Mbox.java:23)
What am I doing wrong?
Related
I'm making a script to turn on and off my lights using email and EVERYTHING works besides the fact that it won't update to the newest email and I don't know why. I couldn't find anything online, and I didn't try anything because I'm completely lost. BTW for more info the first time the script runs it runs the newest email but it doesn't do it again after that
This is my code please help
to my understanding the way the while loop should work is get a subject, then check to see if it matches what im asking it to look for then weather it is or isnt it goes about to the top and checks the most recent subject again then checing if its what im looking for then doing it again and again and again
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 javax.mail.Store;
public class GetEmails {
public static void on(){
SSH on = new SSH();
on.command = "python3 on.py";
on.run();
}
public static void off(){
SSH off = new SSH();
off.command = "python3 off.py";
off.run();
}
public static void check(String host, String storeType, String user,
String password)
{
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
//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
Message[] messages = emailFolder.getMessages();
boolean power = true;
while(true){
int i = messages.length - 1;
Message message = messages[i];
String subject = message.getSubject();
// System.out.println(subject);
if(subject.equals("+myRoom") & power == false){
on();
power = true;
System.out.println("Light on");
}
else if (subject.equals("-myRoom") & power == true){
off();
power = false;
System.out.println("Light Off");
}
else{
continue;
}
}
} 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";// change accordingly
String mailStoreType = "pop3";
String username = "EMAIL#gmail.com";// change accordingly
String password = "PASSWORD";// change accordingly
check(host, mailStoreType, username, password);
}
}
The problem is that you only call getMessages() before the while loop and then continuously check the same set of downloaded messages over and over again in the while-loop.
You need to change the while-loop to download the latest (set of) messages.
I would also point out that your code does not account for the possibility of receiving non-command messages that might push the latest command message into the "not the latest" slot (e.g. latest command message might have index messages.length - 2 while the non-command message has the messages.length - 1 index) nor does it account for the possibility of getting disconnected due to network outages or the server dropping your connection (which happens all the time for any number of reasons).
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
I am getting connection error on WebSphere admin client creation process.
I read many forums but cannot fix it.
"Exception creating Admin Client Connection: com.ibm.websphere.management.exception.ConnectorException: ADMC0016E: The system cannot create a SOAP connector to connect to host "111.xxxx.." at port 8879."
My dmgr port is 8879
Host name is "111.xxxx.."
Servers config files located c:\temp\soap.client.props, DummyClientTrustFile.jks, DummyClientKeyFile.jks
My code is below:
import java.util.Date;
import java.util.Properties;
import java.util.Set;
import javax.management.InstanceNotFoundException;
import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import com.ibm.websphere.management.AdminClient;
import com.ibm.websphere.management.AdminClientFactory;
import com.ibm.websphere.management.exception.ConnectorException;
public class AdminClientConnection
{
private AdminClient adminClient;
public static void main(String[] args)
{
AdminClientConnection aClient = new AdminClientConnection();
// Create an AdminClient
aClient.createAdminClient();
}
private void createAdminClient()
{
// Set up a Properties object for the JMX connector attributes
Properties clientProps = new Properties();
clientProps.setProperty(
AdminClient.CONNECTOR_TYPE, AdminClient.CONNECTOR_TYPE_SOAP);
clientProps.setProperty(AdminClient.CONNECTOR_HOST, "111.xxxx..");
clientProps.setProperty(AdminClient.CONNECTOR_PORT, "8879");
clientProps.setProperty(AdminClient.CONNECTOR_SECURITY_ENABLED, "true");
clientProps.setProperty(AdminClient.USERNAME, "usr");
clientProps.setProperty(AdminClient.PASSWORD, "pass");
clientProps.setProperty(AdminClient.CONNECTOR_SOAP_CONFIG, "c:/temp/soap.client.props");
clientProps.setProperty("javax.net.ssl.trustStore", "c:/temp/DummyClientTrustFile.jks");
clientProps.setProperty("javax.net.ssl.keyStore", "c:/temp/DummyClientKeyFile.jks");
clientProps.setProperty("javax.net.ssl.trustStorePassword", "WebAS");
clientProps.setProperty("javax.net.ssl.keyStorePassword", "WebAS");
// Get an AdminClient based on the connector properties
try
{
adminClient = AdminClientFactory.createAdminClient(clientProps);
}
catch (ConnectorException e)
{
System.out.println("Exception creating Admin Client Connection: " + e);
System.exit(-1);
}
System.out.println("Connected to Application Server");
}
}
Be sure that CONNECTOR_PORT is true, CONNECTOR_SECURITY_ENABLED is not neccassary. Be sure that soap.client.props and jks files are gathered from the connector host.
I have a regular Java Application that works with Javamail. As in, if I just run it in a Main(String[] args) it will work but if I'm running it from a webapp, specifically VAADIN with Tomcat (AND Jetty), I always get a java.net.SocketException: network is unreachable: connect
I can ping the MSExchange server. And the regular program works.
In eclipse, I tried following this guide by changing the server.xml and web.xml settings, but after adding in all th changes, I still get the same error.
This is the Java Application that works in Eclipse, it will send an email using the MSExchange server we have. Are there specific ports I need to add? I've tried to force Tomcat to use IPV4 by adding 0.0.0.0 to all my connectors but that didn't do anything.
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import javax.mail.Session;
import java.text.SimpleDateFormat;
public class SendEmail {
public static void main(String[] args) {
//Creates a connection with the Exchange Server.
String smtpHostServer = "MSExchangeServerName";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.socketFactory.port", "25");
props.put("java.net.preferIPv4Stack","True");
Session session = Session.getInstance(props, null);
String todayStr = new SimpleDateFormat("MM-dd-yyyy").format(new Date());
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, 14);
Date d = c.getTime();
String dateStr = new SimpleDateFormat("MM/dd/yyyy").format(d);
SendEmailUtility.sendEmail(session, "email#host.com", "Test <b>Email</b>");
Here is the SendEmailUtility:
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendEmailUtility {
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
//Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress("blah#test.com"));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toEmail));
// Set Subject: header field
message.setSubject(subject);
// This mail has 2 part, the BODY and the embedded image
MimeMultipart multipart = new MimeMultipart("related");
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<img src=\"cid:image\"><p>"+body;
messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
String fdsImg;
fdsImg = "c:\download.jpg";
DataSource fds = new FileDataSource(fdsImg);
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<image>");
// add image to the multipart
multipart.addBodyPart(messageBodyPart);
// put everything together
message.setContent(multipart);
// Send message
Transport.send(message); //ERROR HAPPENS HERE ON TOMCAT
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This is the exactly same copy pasted code in the webapp with the exact same EmailUtils above, only that this version DOESN'T WORK.
btnSendEmail.addClickListener(new ClickListener(){
#Override
public void buttonClick(ClickEvent event) {
try {
String smtpHostServer = "MSExchangeServerName";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.socketFactory.port", "25");
props.put("java.net.preferIPv4Stack","True");
Session session = Session.getInstance(props, null);
String todayStr = new SimpleDateFormat("MM-dd-yyyy").format(new Date());
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, 14);
Date d = c.getTime();
String dateStr = new SimpleDateFormat("MM/dd/yyyy").format(d);
SendEmailUtility.sendEmail(session, "blah#test.com", "test <b>email");
} catch (Exception e) {
e.printStackTrace();
Notification.show("Error sending the email", Notification.Type.ERROR_MESSAGE);
}
}
});
layout.addComponent(btnSendEmail);
My Stacktrace:
javax.mail.MessagingException: Could not connect to SMTP host: MSExchangeName, port: 25;
nested exception is:
java.net.SocketException: Network is unreachable: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:295)
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 org.test.EmailUtils.sendEmail(EmailUtils.java:57)
Are there any other options I have to do or that I might not have done correctly? As a shot in the dark, I tried looking up eclipse, javamail, tomcat and I got this question and added the Javamail jar to my Tomcat Lib folder and also in my classpath. I still get the cannot connect error.
When I Right Click > Run as >Run on server, I tried to see if Tomcat was running on a system account, but when I checked in Task Manager, it had my Username under here:
Does this mean it has access to the network? Or something is still blocked? Or I need to add proxy settings specifically for Tomcat?
Sounds like a firewall or anti-virus problem. The JavaMail FAQ has connection debugging tips.
I want to read property file on Server side. I have DBConfig.java, useDBConfig.java and DBConfig.properties all placed in server package. I can't read the values from property file on Server Side. Your help is highly appreciated.
public interface DBConfig extends Constants {
#DefaultStringValue("host")
String host(String host);
#DefaultStringValue("port")
String port(String port);
#DefaultStringValue("username")
String username(String username);
#DefaultStringValue("password")
String password(String password);
}
public void useDBConfig() {
DBConfig constants = GWT.create(DBConfig.class);
Window.alert(constants.host());
host = constants.host(host);
port = constants.port(port);
username = constants.username(username);
password = constants.password(password);
}
property file...
host=127.0.0.1
port=3306
username=root
password=root
Thanks in advance.
GWT.Create can be used only in client mode.
Are you sure that code execute in server side?
If i write in my application GWT.Create in server side i get this error:
java.lang.UnsupportedOperationException: ERROR: GWT.create() is only usable in client code! It cannot be called, for example, from server code. If you are running a unit test, check that your test case extends GWTTestCase and that GWT.create() is not called from within an initializer or constructor.
You can read a properties files in java. The file is similar that Constants files in GWT.
Example of Properties file:
key = value
host = 127.0.0.1
port = 80
username = guest
password = guest
EOF
You can read this file, see the next code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
String fileToRead = "MY_PATH"+File.separator+"MY_FILE.properties";
Properties prop = new Properties();
try {
File propertiesFile = new File(fileToRead);
prop.load(new FileInputStream(propertiesFile));
String host = prop.getProperty("host");
String port = prop.getProperty("port");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(host);
System.out.println(port);
System.out.println(username);
System.out.println(password);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If the key doesnt exists getProperty(String key) return null.
You can use prop.containsKey(String key); to see if the key exists. This function return a boolean (True if exists False in other case).
Greetings