How to fix Java Mail not displaying new emails in while loop - java

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).

Related

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

Gammu send sms using two or more java app from ssh at the same time

I'm using gammu to send sms, and I was wondering if it is possible to send messages at the same time using two or more computer with java app. I tried it 10 times and 1 out of 10 times the message successfully sent from both computer. 9 times only one computer can send the sms with the other one failing to send.
Is there some kind of setting or command so I can send message from both of this computers at the same time? For the config I use the default config from Gammu
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class TestingSms {
public static void main(String[] args) {
// TODO Auto-generated method stub
String host = "MY GAMMU IP";
String user = "MY USERNAME";
String password = "MY PASSWORD";
int port = 22;
String sms ="haloo";
JSch jsch = new JSch();
try {
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelExec exec = (ChannelExec) session.openChannel("exec");
exec.setCommand("gammu sendsms TEXT 08xxxxxxxxxx -text \""+sms+"\"");
exec.setErrStream(System.err);
exec.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
String temp;
while((temp=reader.readLine())!=null) {
System.out.println(temp);
}
exec.disconnect();
session.disconnect();
System.out.println("\n\nFinish");
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Failed Message:
Warning: No configuration read, using builtin defaults!
No response in specified timeout. Probably phone not connected.
Thank you in advance
Maybe you rather want to use Gammu SMSD for this - it runs on the server and sends/receives messages from/to database. This way you can easily send messages from other hosts just by inserting them to the database.
The error Warning: No configuration read, using builtin defaults! indicates that Gammu didn't find the configuration file, maybe you're running it as different user? Or try to specify path to configuration file using --config parameter.

Java : Using Javamail to read email

I've been working on a program, that's suppose to use javamail, to read through an inbox, and if an email contains a specific String, it should be opened.
First off, this is my first time trying to use this javamail api - I'm pretty sure that my properties are all messed up - Can anyone give me at tip on correctly setting up properties for javamail?
Secondly, it seems like i can connect via the API, but if I try to search for subjects AND the subject is null, I get a null pointer exception - If I however don't try to match the subject with "Ordretest", I get no nullpointer - Any tips would be a great help :)
package vildereMail;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.search.FromTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
public class vildereMail {
public boolean match(Message message) {
try {
if (message.getSubject().contains("Ordretest")) {
System.out.println("match found");
return true;
}
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
};
public static void main(String[] args) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
props.put("mail.imap-mail.outlook.com.ssl.enable", "true");
props.put("mail.pop3.host", "outlook.com");
props.put("mail.pop3.port", "995");
props.put("mail.pop3.starttls.enable", "true");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap-mail.outlook.com", "myEmail#live.dk", "MyPassword");
session.setDebug(true);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
SearchTerm sender = new FromTerm(new InternetAddress("myMail#live.dk"));
Message[] messages = inbox.search(sender);
System.out.println(messages);
for (int i = 0 ; i < messages.length ; i++) {
System.out.println(messages[i].getSubject());
if (messages[i].getSubject().equals(null)) {
System.out.println("null in subject");
break;
}
else if (messages[i].getSubject().contains("Ordretest")){
System.out.println("1 match found");
}
else {
System.out.println("no match");
}
}
System.out.println("no more messages");
store.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}
}
Without knowing on which line you get the NPE (Null Pointer Exception) I guess it occurs here:
if (messages[i].getSubject().equals(null))
If getSubject() returns null and you try to do .equals() it will throw a NPE (because you try to invoke a method).
So try to rewrite it to (assuming your message object can't be null):
if (messages[i].getSubject() == null)
Where to start...
Have you found the JavaMail FAQ?
You can get rid of all the property settings because they're doing nothing since you're using the "imaps" protocol, not the "pop3" protocol.
As others have explained, the getSubject method might return null, so you need to check for that.

Can't connect to mbox store

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?

Can't read property file on Server side with GWT

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

Categories

Resources