Could you please help with follow?
I need to open each email that I have in my Inbox.
Get a content from it.
public void main() {
driver.get("https://mail.google.com");
// gmail login
driver.findElement(By.id("Email")).sendKeys("email");
driver.findElement(By.id("next")).click();
driver.findElement(By.id("Passwd")).sendKeys("password");
driver.findElement(By.id("signIn")).click();
List<WebElement> unreademeil = driver.findElements(By.xpath("//*[#class='zF']"));
// Mailer name for which i want to check do i have an email in my inbox
String MyMailer = "Команда Gmail";
// real logic starts here
for(int i=0;i<unreademeil.size();i++){
if(unreademeil.get(i).isDisplayed()==true){
if(unreademeil.get(i).getText().equals(MyMailer)){
System.out.println("Yes we have got mail form " + MyMailer);
break;
}else{
System.out.println("No mail form " + MyMailer);
}
}
}
//open a mail from the gmail inbox.
List<WebElement> a = driver.findElements(By.xpath("//*[#class='yW']/span"));
System.out.println(a.size());
for (int i = 0; i < a.size(); i++) {
System.out.println(a.get(i).getText());
if (a.get(i).getText().equals("Я")) //to click on a specific mail.
{
a.get(i).click();
System.out.println(driver.findElement(By.xpath("//*[#id=\":9v\"]/div[1]")).getText());
driver.navigate().back();
}
}
I've tried JavaMail API as well.
But it seems that I do something wrong in their code.
public static void bot() throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "#gmail.com",
"password");
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
System.out.println("Total Message:" + folder.getMessageCount());
System.out.println("Unread Message:"
+ folder.getUnreadMessageCount());
Message[] messages = null;
boolean isMailFound = false;
Message mailFromGod= null;
//Search for mail from God
for (int i = 0; i < 5; i++) {
messages = folder.search(new SubjectTerm("t");
folder.getMessages());
//Wait for 10 seconds
if (messages.length == 0) {
Thread.sleep(10000);
}
}
for (Message mail : messages) {
if (!mail.isSet(Flags.Flag.SEEN)) {
mailFromGod = mail;
System.out.println("Message Count is: "
+ mailFromGod.getMessageNumber());
isMailFound = true;
}
}
String line;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(
new InputStreamReader(mailFromGod
.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
System.out.println(buffer);
String registrationURL = buffer.toString().split("http://www./?")[0]
.split("href=")[1];
System.out.println(registrationURL);
}
}
}
and try this
package Bots;
import javax.mail.*;
import java.util.Properties;
public class checkemail {
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 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());
//System.out.println("Message" + message.getDescription().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";// change accordingly
String mailStoreType = "pop3";
String username = "test#gmail.com";// change accordingly
String password = "test";// change accoredingly
check(host, mailStoreType, username, password);
}
}
Result:
...
Email Number 7
Subject: test
From: Google
Text: javax.mail.internet.MimeMultipart#612fc6eb
Email Number 8
Subject: test
From: Google
Text: javax.mail.internet.MimeMultipart#1060b431
but how to get normal text from the message
message.getContent().toString()
Above code works for plain text for multipart messages please include below piece of code in you for loop.
Multipart multipart = (Multipart) message.getContent();
for (int j = 0; j < multipart.getCount(); j++) {
BodyPart bodyPart = multipart.getBodyPart(j);
System.out.println("Body: "+bodyPart.getContent());
content= bodyPart.getContent().toString();
System.out.println(content);
}
Lets update if your issue resolves by this.
I've modified code a bit. Everything seems to be working as expected.
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class email {
private WebDriver driver;
#BeforeMethod
public void beforeMethod() {
String exePath = "chromedriver_win32\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", exePath);
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://google.com/");
}
#AfterMethod
public void afterMethod() {
driver.quit();
}
#Test
public void main() throws InterruptedException {
String email = "email";
String password = "password";
driver.get("https://mail.google.com");
driver.findElement(By.id("Email")).sendKeys(email);
driver.findElement(By.id("next")).click();
driver.findElement(By.id("Passwd")).sendKeys(password);
driver.findElement(By.id("signIn")).click();
// now talking un-read email form inbox into a list
List<WebElement> unreademeil = driver.findElements(By.xpath("//*[#class='zF']"));
// Mailer name for which i want to check do i have an email in my inbox
String MyMailer = "FROMTESTEMAIL";
String bodyemail = "";
int i = 0;
for (i = 0; i < unreademeil.size(); i++) {
if (unreademeil.get(i).isDisplayed() == true) {
unreademeil.get(i).click();
System.out.println(bodyemail);
driver.findElement(By.xpath("//a[contains(text(),'Click here')]")).click();
Thread.sleep(5000);
System.out.println("Your current page is: " + driver.getTitle());
ArrayList<String> tabs2 = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs2.get(0));
driver.close();
driver.switchTo().window(tabs2.get(1));
System.out.println("Your current page is: " + driver.getTitle());
driver.findElement(By.xpath("/html/body/div/div[5]/div[2]/div[1]/a")).click();
System.out.println("It is started");
Thread.sleep(3000);
// do something after clicking on the required link
// ...
try {
Alert confirmationAlert = driver.switchTo().alert();
String alertText = confirmationAlert.getText();
System.out.println("Alert text is " + alertText);
confirmationAlert.accept();
} catch (Exception e) {
System.out.println("The alerts haven't been found");
e.printStackTrace();
}
driver.get("https://mail.google.com");
Thread.sleep(5000);
i--;
unreademeil = driver.findElements(By.xpath("//*[#class='zF']"));
}
}
}
}
Related
I need to implement a program to transfer files. I decided to make it using a chat template I've made about 1 month ago so I would have a chat with file transfer option.
The transfer should follow the following points:
1- Server only keeps a list of all files provided by connected clients (No file are actually located in the server, only their names)
2- Client "1" requests file "A" then:
if file "A" is located ONLY in client "2", then client "2" should send 100% of the file to client "1"
if file "A" is located in client "2" and client "3" also has file "A", then client "2" should send 50% of the file to client "1" and client "3" should send the other 50%.
(if the file is located in 4 clients it should be 25% each....and so it goes...)
I've already managed to make the server find out which client is requesting the file and which clients have it. But now I'm stuck, I don't know how to make the transfer.
Could someone give me an example of how to do it? or point me through the right direction?
[I'm aware my code has some flaws and I will fix it later, right now I need to make the transfer happen before working on fixes, so please, unless it's related, try to focus on that]
Server:
package tor;
import java.util.*;
import java.io.*;
import java.net.*;
public class Server extends Thread {
private String cname;
private Socket client;
public static Vector<PrintStream> clients;
public static Vector<String> clientnames;
public static Vector<String> archives;
public Server(Socket client) {
this.client = client;
}
public static void main(String[] args) {
clients = new Vector<PrintStream>();
clientnames = new Vector<String>();
archives = new Vector<String>();
try {
ServerSocket server = new ServerSocket(2391);
System.out.println("Server Started!!\n");
while (true) {
Socket client = server.accept();
Server s = new Server(client);
s.start();
}
} catch (IOException e) {
System.out.println("Server could not start ");
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream out = new PrintStream(client.getOutputStream());
cname = in.readLine();
System.out.println(cname + " Connected --- SERVER!");
if (cname == null) {
System.out.println("Unknown Name");
return;
}
clientnames.add(cname);
clients.add(out);
connected(" ********** [", cname, "] Connected! **********");
String arq;
int size = in.read();
System.out.println(size);
for (int i = 0; i < size; i++) {
arq = in.readLine();
archives.add(arq);
}
String msg = in.readLine();
String selected;
while (true) {
while (!(msg).equals("/exit") && !(msg).equals("/Exit") && !(msg).equals("/EXIT")) {
if ((msg).equals("/list") || (msg).equals("/List") || (msg).equals("/list")) {
out.println("-------- Archives List --------");
for (int i = 0; i < archives.size(); i++) {
out.println(i+"- "+archives.get(i));
}
out.println("-------- ******************* --------");
msg = in.readLine();
} else if (msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))){
msg = in.readLine();
int gnum = Integer.parseInt(msg);
selected=archives.get(gnum);
returnAll("[", out, "]: ", "idreq");
out.println("1");
reqAll(selected);
// I BELIVE HERE IS THE RIGHT PLACE TO MAKE DE TRANSFER CODE
msg = in.readLine();
} else {
returnAll("[", out, "]: ", msg);
msg = in.readLine();
}
}
msg = in.readLine();
size = Integer.parseInt(msg);
for (int i = 0; i <= size; i++) {
arq = in.readLine();
for(int j=0;j<archives.size();j++) {
if (archives.get(j).equals(arq)) {
archives.remove(j);
}
}
}
returnAll(" ********** [", out, "] disconnected ", " ********** ");
clients.remove(out);
clientnames.remove(cname);
client.close();
break;
}
} catch (IOException e) {
System.out.println("A Client disconnected ");
}
}
// METHOD TO SEND CONNECTION MESSAGE
public void connected(String msg1, String cname, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + msg2);
}
}
// METHOD TO RETURN MESSAGE TO ALL CLIENTS
public void returnAll(String msg1, PrintStream saida, String ac, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + ac + msg2);
}
}
public void reqAll(String req) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(req);
}
}
}
Client:
package tor;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Client extends Thread {
private Socket con;
private static boolean done = false;
static ArrayList<String> localArq = new ArrayList<String>();
static int c=0;
public Client(Socket s) {
con = s;
}
public static void main(String[] args) {
try {
String ip;
Scanner s = new Scanner(System.in);
System.out.print("Enter Server's IP: ");
ip =s.next();
Socket con = new Socket(ip, 2391);
PrintStream out = new PrintStream(con.getOutputStream());
System.out.println("Connected to Server!");
System.out.print("Enter your Nickname: ");
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
String cname = scan.readLine();
out.println(cname);
String dir="C:\\javator\\"+cname;
Thread t = new Client(con);
t.start();
File folder = new File(dir);
folder.mkdir();
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
localArq.add(listOfFiles[i].getName());
}
}
int size=localArq.size();
out.write(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
String msg;
while (true) {
System.out.print("");
msg = scan.readLine();
if(msg.equals("/ll")) {
System.out.println("-------- LOCAL LIST --------");
for (int i = 0; i < localArq.size(); i++) {
System.out.println(localArq.get(i));
}
System.out.println("-------- ******************* --------");
msg = scan.readLine();
}else if(msg.equals("/exit") || (msg.equals("/Exit")) || (msg.equals("/EXIT"))) {
out.println(msg);
size=localArq.size();
out.println(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
}
else if(msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))) {
System.out.println("Chose file's number to /get: ");
c++;
}
if (done == true) {
break;
}
out.println(msg);
}
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String rmsg;
String req;
while (true) {
rmsg = in.readLine();
if (rmsg == null) {
System.out.println("Connection Terminated");
break;
}else if(rmsg.substring(rmsg.length() - 5).equals("idreq")) {
req = in.readLine();
for(int i=0;i<localArq.size();i++) { //IDENTIFIES WHO OWNS THE REQUESTED FILE
if(localArq.get(i).equals(req)) {
System.out.println("Owns requested file");
Socket requester = new Socket("192.168.3.114", 2007);
ObjectOutputStream outputr = new ObjectOutputStream(requester.getOutputStream());
ObjectInputStream inputr = new ObjectInputStream(requester.getInputStream());
Object mens= inputr.readObject();
System.out.println(mens);
outputr.writeObject("OWNER FOUND");
}
}
if(c==1) { //IDENTIFIES WHO WANTS THE FILE
rmsg = in.readLine();
c= Integer.parseInt(rmsg);
System.out.println("file: "+req);
ServerSocket peer = new ServerSocket(2007);
System.out.println("OPEN FOR CONNECTIONS\n");
Socket client = peer.accept();
System.out.println("Client connected: " + client.getInetAddress().getHostAddress());
ObjectOutputStream outputo = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream inputo = new ObjectInputStream(client.getInputStream());
outputo.flush();
outputo.writeObject("Connected to requester");
Object mens= inputo.readObject();
System.out.println(mens);
}
}
else {
System.out.println(rmsg);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
done = true;
}
}
I was able to make a transfer between two clients easily with the information provided and a little research on stackOverflow to understand more about out/inputStreams!
This post also helped me a lot: Sending a file with Java Sockets, losing data
next step is the shared transfer
I am sending an outlook invitation using java mail to four different email servers:
web.de
gmx.net
gmail.com
company's private email server (which is configured on outlook)
The invitation is rendered/previewed on gmail only but we need to render/preview it on every platform.
My main class is
public class Email {
// Constants for the ICalendar methods.
public static final String METHOD_CANCEL = "CANCEL";
public static final String METHOD_PUBLISH = "PUBLISH";
public static final String METHOD_REQUEST = "REQUEST";
// Apply this organizer, if no organizer is given.
private static final String DEFAULT_ORGANIZER = "zain#company.com";
// Common ICalendar fields.
private String method;
private Calendar beginDate;
private Calendar endDate;
private String location;
private int uid;
private String description;
private String subject;
private String organizer;
/*
* #param args
*/
public static void main(String[] args) {
try {
Email email = new Email();
email.send();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
public void send() throws Exception {
try {
String from = "mansoor#company.com";
Properties prop = new Properties();
Address[] receivers = new InternetAddress[] {
new InternetAddress("abc#company.com")
, new InternetAddress("abc#gmail.com")
, new InternetAddress("abc#web.de")
, new InternetAddress("abc#gmx.de")
};
prop.put("mail.transport.protocol", "smtp");
prop.put("mail.smtp.host", "smtp.company.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("smtp#company.com", "password");
}
};
Session session = Session.getDefaultInstance(prop, authenticator);
// Define message
MimeMessage message = new MimeMessage(session);
message.addHeaderLine("method=REQUEST");
message.addHeaderLine("charset=UTF-8");
message.addHeaderLine("component=VEVENT");
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, receivers);
message.setSubject("Outlook Meeting Request Using JavaMail");
this.subject = "Meeting Request Test Subject";
this.description = "PLEASE IGNORE THIS MAIL AS IT IS A TEST.";
this.beginDate = new GregorianCalendar(2018, 07-01, 17, 19, 00);
this.endDate = new GregorianCalendar(2018, 07-01, 17, 19, 45);
this.method = Email.METHOD_REQUEST;
this.location = "Office # 13";
// Create the calendar part
BodyPart calendarPart = new MimeBodyPart();
// Fill the message
calendarPart.setHeader("Content-Class", "urn:content- classes:calendarmessage");
calendarPart.setHeader("Content-ID", "calendar_message");
calendarPart.setHeader("Content-Disposition", "inline;filename=Test_invite1.ics");
calendarPart.setFileName("Test_invite1");
calendarPart.setDataHandler(
new DataHandler(
new ByteArrayDataSource(createMessage(), "text/calendar")));// very important
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(calendarPart);
// Put parts in message
message.setContent(multipart);
// send message
Transport.send(message);
for(Address receiver: receivers){
System.out.println(receiver);
}
} catch (MessagingException me) {
System.out.println("Failed sending email");
me.printStackTrace();
} catch (Exception ex) {
System.out.println("Failed sending email");
ex.printStackTrace();
} finally {
System.out.println("End sending email");
System.exit(0);
}
}
public String createMessage() {
// Create the proper date format string required by the ICalendar spec.
final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
final String stringBeginDate = formatter.format(beginDate.getTime());
final String stringEndDate = formatter.format(endDate.getTime());
// Encode the description => mark new lines.
final String encodedDescription = description.replaceAll("\r\n", "\\\\n");
// Use the default organizer if none is given.
if (this.organizer == null) {
this.organizer = DEFAULT_ORGANIZER;
}
// Content string as array.
String[] contents = {
"BEGIN:VCALENDAR",
"METHOD:" + this.method,
"BEGIN:VEVENT",
"UID:" + this.uid,
"DTSTART:" + stringBeginDate,
"DTEND:" + stringEndDate,
"LOCATION:" + this.location,
"DESCRIPTION:" + encodedDescription,
"ATTENDEE;RSVP=TRUE:MAILTO:" + this.organizer,
"ORGANIZER:" + this.organizer,
"SUMMARY:" + this.subject,
"END:VEVENT",
"END:VCALENDAR"
};
// Build a well-formatted string from the array.
StringBuilder sb = new StringBuilder();
for (String line : contents) {
if (sb.length() > 0) {
sb.append("\n");
}
sb.append(line);
}
return sb.toString();
}
}
Please add comment if you have any ambiguity before down voting. I have seen so many question on stackoverflow.com but found no proper solution.
I have to create multiple client threads and each one has to login .and i have implemented user_login function as synchronized but when i am calling it in run method of thread ,multiple threads are accessing it same time.I want that only one client should do login first then second and so on...
import java.io.*;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
class Login {
private String username = ""; //username of server manager
private String password = ""; //password of server manager
private String record = "";
private boolean flag = false;
public synchronized String user_login() {
Logger logger; //Reference to Logger class is generated
Handler fileHandler;
SimpleFormatter plainText;
Scanner s;
int thread_name = 0;
try {//login details fetched from login.txt file
BufferedReader br = new BufferedReader(new FileReader("D:/JAVA/assignment1/Login.txt"));
s = new Scanner(System.in);
System.out.println("Enter your username: ");
username = s.nextLine();
System.out.println("Enter your password: ");
password = s.nextLine();
Scanner scan;
while ((record = br.readLine()) != null) { //records fetched line by line
String[] split = record.split(" ");
if (username.equals(split[0]) && password.equals(split[1])) //username and password compared with data fetched
{
System.out.println(" LOGIN SUCCESSFULL for" + thread_name);
flag = true;
logger = Logger.getLogger(Logger.class.getName());
logger.setUseParentHandlers(false);
File f = new File("D:/JAVA/assignment1/" + username + ".txt");
if (!f.exists())
f.createNewFile();
fileHandler = new FileHandler("D:/JAVA/assignment1/" + username + ".txt", true);//File for writting log is opened in append mode
plainText = new SimpleFormatter();
fileHandler.setFormatter(plainText);
logger.addHandler(fileHandler);
logger.info("User " + username + "logged in");
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (flag == false) {
System.out.println("LOGIN UNSUCCESSFULL!!!! ");
System.out.println("Try again: ");
user_login(); //if login fails,user reenter his details
}
return username;
}
}
public class Client_Thread extends Thread {
static String username = ""; //username of server manager
//password of server manager
String record = "";
static String locationname;
static boolean flag = false;
Logger logger; //Reference to Logger class is generated
int thread_name = 0;
Client_Thread(int x) {
thread_name = x;
}
#Override
public void run() //client thread statrs execution
{
System.out.println(this.thread_name);
try {
Login l = new Login();
synchronized(l)
{
username = l.user_login();
}
locationname = username.substring(0, 3);
if (locationname.equals("MTL")) //checks which server's manager logged in
{
Registry reg;
reg = LocateRegistry.getRegistry(2964);
ServerInterface ms = (ServerInterface) reg.lookup("Mtl"); //looks for reference Mtl in registry for montreal server
Operations m = new Operations();
m.Operations1(ms,username); //performs the required function
//logger.info(Logger.class.getName());
} else if (locationname.equals("LVL")) {
Registry reg = LocateRegistry.getRegistry(2965);
ServerInterface ls = (ServerInterface) reg.lookup("Lvl"); //looks for reference Lvl in registry for laval server
Operations m = new Operations();
m.Operations1(ls,username);//performs the required function
} else if (locationname.equals("DDO")) {
Registry reg = LocateRegistry.getRegistry(2966);
ServerInterface ds = (ServerInterface) reg.lookup("Ddo"); //looks for reference Ddo in registry for DDO server
Operations m = new Operations();
m.Operations1(ds,username); //performs the required function
}
} catch (IOException | NotBoundException e1) {
e1.printStackTrace();
}
}
}
public class Client {
static void test_case1()
{
for(int i=0;i<2;i++)
{
Client_Thread c = new Client_Thread(i); //run the new client thread
c.start();
}
}
public static void main(String arg[]) throws RemoteException, NotBoundException {
test_case1();
}
}
output is like this:-
0
1
Enter your username:
Enter your username:
but i should be like:-
Enter your username:
Enter your password:
Each one of your threads creates its own Login object.
Therefore, synchronization has no effect, because each thread synchronizes on a different instance of your Login object.
In order to achieve the desired behavior you have to instantiate only one Login object and pass it to all your threads to use.
public class testemail {
Properties properties = null;
private Session session = null;
private Store store = null;
private Folder inbox = null;
private String userName = "xxx#gmail.com"; //
private String password = "xxx";
public testemail() {
}
public void readMails() throws Exception {
properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
store = session.getStore("imaps");
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
System.out.println("Number of mails = " + messages.length);
for ( Message message : messages ) {
Address[] from = message.getFrom();
System.out.println("-------------------------------");
System.out.println("Date : " + message.getSentDate());
System.out.println("From : " + from[0]);
System.out.println("Subject: " + message.getSubject());
System.out.println("Content :");
Object content = message.getContent();
Multipart multiPart = (Multipart) content;
procesMultiPart(multiPart);
System.out.println("--------------------------------");
}
inbox.close(true);
store.close();
}
catch (NoSuchProviderException e)
{
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void procesMultiPart(Multipart content) throws Exception {
int multiPartCount = content.getCount();
for (int i = 0; i < multiPartCount; i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println(o);
} else if (o instanceof Multipart) {
procesMultiPart((Multipart) o);
}
}
}
public static void main(String[] args) throws Exception {
testemail sample = new testemail();
sample.readMails();
}}
In the above code I am able to get emails from oldest to newest on my console from gmail. However I would want it to loop from newest to oldest. Is there any way I could get this achieved. Please Help :)
I don't think there's a parameter or method for this in the JavaMail API. You have to reverse the messages array yourself, e.g. by including the Commons.Lang library:
messages = ArrayUtils.reverse(messages);
or iterating over it in the other direction:
for (int i = messages.length - 1; i >= 0; i--) {
Message message = messages[i];
I have this simple code to perdiodically access a pop3 server and check if there are new messages in the inbox folder
public static void main(String[] args) {
try {
String storeType = "pop3";
String host = "...";
int port = ...;
String user = "...";
String psw = "...";
//
int delay = 1;
long mins = 200 * 60 * delay;
firstAccess = true;
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.user", user);
properties.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.pop3.port", port);
RomasAuthenticator r = new RomasAuthenticator(user, psw);
Session session = Session.getDefaultInstance(properties, r);
POP3Store emailStore = (POP3Store) session.getStore(storeType);
emailStore.connect(host, port, user, psw);
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
while (true) {
if (checkInbox(emailFolder)) {
//prepara la notifica per il voice_service
System.out.println("mes!");
}
firstAccess = false;
Thread.sleep(mins);
}
} catch (Exception ex) {
//return null;
}
}
private static boolean checkInbox(Folder inbox_folder) throws MessagingException, IOException {
System.out.println("checking");
boolean res = false;
try {
int email_actual_count = inbox_folder.getMessageCount();
if (email_actual_count > email_prev_count /*or hasNewMessages()*/) {
if (!firstAccess) {
res = true;
}
}
//bisogna aggiornare comunque email_count in caso siano stati cancellati messaggi
email_prev_count = email_actual_count;
}
catch (Exception e) {
e.printStackTrace();
}
return res;
}
Both getMessageCount() and hasNewMessages() do not work, because the first always returns the same number of messages, and the second always returns false. What's that I'm doing wrong?
I don't want to use a messagelistener because this code will run on a robot with really low performances..
thanks everyone
The JavaMail FAQ explains why these features don't work with the POP3 protocol.