Send email to arraylist retrieved from database - java

I am working on a project where I am required to retrieve email addresses from database and then send an email to them. I have retrieved those email addresses in arraylist. Like this:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javaapplication1.Person;
public class ABC {
public static void main(String[] args) throws SQLException {
ArrayList<Person> personlist = new ArrayList<Person>();
//List<Person> personlist = new List<Person>();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","gsjsc","gsjschanna");
Statement st=con.createStatement();
ResultSet srs = st.executeQuery("SELECT * FROM person2");
while (srs.next()) {
Person person = new Person();
person.setName(srs.getString("name"));
person.setJobtitle(srs.getString("jobtitle"));
// person.setFrequentflyer(srs.getInt("frequentflyer"));
personlist.add(person);
}
System.out.println(personlist.size());
for (int a=0;a<personlist.size();a++)
{
System.out.println(personlist.get(a).getName());
System.out.println(personlist.get(a).getJobtitle());
// System.out.println(personlist.get(2).getName());
// System.out.println(personlist.get(3).getName());
}
//System.out.println(personlist.get(4));
//System.out.println(namelist.);
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Person.java: contains all setters and getters.
EDIT
Now I have to send emails to those email addresses retrieved in the arraylist of object person.
I have got a code for sending emails to multiple recipients in arraylist like this:
package javaapplication1;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmailToGroupDemo {
public static void main(String[] args) {
// Create a SendEmail object and call start
// method to send a mail in Java.
SendEmailToGroupDemo sendEmailToGroup = new SendEmailToGroupDemo();
sendEmailToGroup.start();
}
private void start() {
// For establishment of email client with
// Google's gmail use below properties.
// For TLS Connection use below properties
// Create a Properties object
Properties props = new Properties();
// these properties are required
// providing smtp auth property to true
props.put("mail.smtp.auth", "true");
// providing tls enability
props.put("mail.smtp.starttls.enable", "true");
// providing the smtp host i.e gmail.com
props.put("mail.smtp.host", "smtp.gmail.com");
// providing smtp port as 587
props.put("mail.smtp.port", "587");
// For SSL Connection use below properties
/*props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");*/
// Create Scanner object to take necessary
// values from the user.
Scanner scanner = new Scanner(System.in);
System.out.println("Please provide your Username for Authentication ...");
final String Username = scanner.next();
System.out.println("Please provide your Password for Authentication ...");
final String Password = scanner.next();
System.out.println("Please provide Email Address from which you want to send Email ...");
final String fromEmailAddress = scanner.next();
System.out.println("Please provide Email Addresses to which you want to send Email ...");
System.out.println("If you are done type : Done or done");
// ArrayLists to store email addresses entered by user
ArrayList< String> emails = (ArrayList< String >) getEmails();
System.out.println("Please provide Subject for your Email ... ");
final String subject = scanner.next();
System.out.println("Please provide Text Message for your Email ... ");
final String textMessage = scanner.next();
// Create a Session object based on the properties and
// Authenticator object
Session session = Session.getDefaultInstance(props,
new LoginAuthenticator(Username,Password));
try {
// Create a Message object using the session created above
Message message = new MimeMessage(session);
// setting email address to Message from where message is being sent
message.setFrom(new InternetAddress(fromEmailAddress));
// setting the email addressess to which user wants to send message
message.setRecipients(Message.RecipientType.BCC, getEmailsList(emails));
// setting the subject for the email
message.setSubject(subject);
// setting the text message which user wants to send to recipients
message.setText(textMessage);
// Using the Transport class send() method to send message
Transport.send(message);
System.out.println("\nYour Message delivered successfully ....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
// This method takes a list of email addresses and
// returns back an array of Address by looping the
// list one by one and storing it into Address[]
private Address[] getEmailsList(ArrayList< String > emails) {
Address[] emaiAddresses = new Address[emails.size()];
for (int i =0;i < emails.size();i++) {
try {
emaiAddresses[i] = new InternetAddress(emails.get(i));
}
catch (AddressException e) {
e.printStackTrace();
}
}
return emaiAddresses;
}
// This method prompts user for email group to which he
// wants to send message
public List< String > getEmails() {
ArrayList< String > emails = new ArrayList< String >();
int counter = 1;
String address = "";
Scanner scanner = new Scanner(System.in);
// looping inifinitely times as long as user enters
// emails one by one
// the while loop breaks when user types done and
// press enter.
while(true) {
System.out.println("Enter E-Mail : " + counter);
address = scanner.next();
if(address.equalsIgnoreCase("Done")){
break;
}
else {
emails.add(address);
counter++;
}
}
return emails;
}
}
// Creating a class for Username and Password authentication
// provided by the user.
class LoginAuthenticator extends Authenticator {
PasswordAuthentication authentication = null;
public LoginAuthenticator(String username, String password) {
authentication = new PasswordAuthentication(username,password);
}
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
This one is a whole different code. But works to send an email to group of people. But problem is we have to enter the email addresses manually. Whereas I want to send the mails to the addresses retrieved from class ABC. Somebody can give me an integrated code (for both the classes) , that would be great.

This should convert a List of Person in an ArrayList of String with the emails from all the persons.
public ArrayList<String> getEmailsFromPersons(List<Person> persons) {
ArrayList<String> emails = new ArrayList<String>();
for(Person person : persons) {
String email = person.getEmail();
if(email != null && !email.trim().isEmpty()) {
emails.add(email);
}
}
return emails;
}

I have retrieved those email addresses in arraylist. Like this:
I do not see any email being set in the Person object. But would still try to answer your question from what I have understood after your edit. Below code should suit your needs (Please don't mind any errors as I am writing it on the fly without any checking):
public class ABC {
public static void main(String[] args) throws SQLException {
ArrayList<Person> personlist = new ArrayList<Person>();
// Creating a separate list of emails for Persons
List<String> personEmails = new ArrayList<String>();
//List<Person> personlist = new List<Person>();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","gsjsc","gsjschanna");
Statement st=con.createStatement();
ResultSet srs = st.executeQuery("SELECT * FROM person2");
String email = "";
while (srs.next()) {
Person person = new Person();
person.setName(srs.getString("name"));
person.setJobtitle(srs.getString("jobtitle"));
// person.setFrequentflyer(srs.getInt("frequentflyer"));
// I am assuming you would be setting email in person like this
email = srs.getString("email");
person.setEmail(email);
// Add the email simultaneously to the separate list
personEmails.add(email);
personlist.add(person);
}
System.out.println(personlist.size());
for (int a=0;a<personlist.size();a++)
{
System.out.println(personlist.get(a).getName());
System.out.println(personlist.get(a).getJobtitle());
// System.out.println(personlist.get(2).getName());
// System.out.println(personlist.get(3).getName());
}
//System.out.println(personlist.get(4));
//System.out.println(namelist.);
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
// call the email sender method of yours with the newly created list
SendEmailToGroupDemo sendEmailToGroup = new SendEmailToGroupDemo();
// Obviously, make that start() method public having parameter of type List<String> instead of calling getEmails() within it
sendEmailToGroup.start(personEmails);
// Very little remains to be done, I hope you can figure it out easily
}
}

Related

Java multithread app not running methods

I'm developing an email application with Java, and I'm trying to implement a Java Thread Pool to break the process into multiple threads.
I have 10 threads to try and send email to multiple recipients, my problem now is that when I run my code it displays the number of threads I have in the pool and ignores to execute my methods in the class.
This is my code:
package system.soft.processor;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import system.source.DjadeUtil;
public class MailTransporter {
// HERE WE SET PUBLIC VARIABLES
private SetBase Setting;
private String[] Mails;
private String Messaging;
private String Title;
private static final String TEMPLATESOURCE="data/templates/vs1/newslatter.php";
// LETS CONSTRUCT MAIN CLASS
public MailTransporter(String[] mails, SetBase setting){
Setting=setting;
Mails=mails;
};
/********************** SETTING THE GETTERS METHODS ************************/
public void subject(String subject){
Title=subject;
}
public void message(String message){
Messaging=message;
}
/********************** CONSTRUCTING THE SEND METHOD ***********************/
public static void main(String[] args){
// HERE WE CONSTRUCT THE SEND
SetBase setting=new SetBase();
String[] mails={"gettrafficworld#yahoo.com", "chineduweb#gmail.com"};
String title="Testing Dynamic Message";
String message="This is the body of the message";
int NUM_THREADS=Integer.parseInt(setting.get("maxThread"));
MailTransporter transport=new MailTransporter(mails, setting);
transport.subject(title);
transport.message(message);
// Create a thread pool
ExecutorService es = Executors.newFixedThreadPool(NUM_THREADS);
List<Future<Integer>> futures = new ArrayList<>(NUM_THREADS);
// Submit task to every thread:
for (int i = 0; i < NUM_THREADS; i++) {
futures.add(i, es.submit((Callable<Integer>) new Transporter(transport)));
}
// Shutdown thread pool
es.shutdown();
System.out.println(futures.size());
}
/********************** CONSTRUCTING THE TRANSPORT METHOD ***********************/
private Integer transport(String[] mails, String title, String messaging){
// HERE WE START PROCESSING THE TRANSPORT
Integer sent=0;
// HERE WE START PROCESSING
// Sender's email ID needs to be mentioned
String from = Setting.get("from");
// Get system properties
Properties properties = props();
System.out.println(properties);
// Get the default Session object.
Session session = session(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.addRecipients(Message.RecipientType.TO, mailAddress(mails));
// Set Subject: header field
message.setSubject(Title);
// Send the actual HTML message, as big as you like
message.setContent(msgTranslate(Title, Messaging), "text/html");
// Send message
Transport.send(message);
// Setting the message return
sent=mails.length;
} catch (MessagingException mex) {
mex.printStackTrace();
}
// Here we return int
return sent;
}
/******************* CONSTRUCTING THE MESSAGE TRANSLATOR ********************/
private String msgTranslate(String subject, String messaging){
// HERE WE START CONSTRUCTING THE MESSAGE TRANSLATE
String data="";
DjadeUtil util=new DjadeUtil();
// NOW LETS START PROCESSING
if(messaging!=null && subject!=null){
// Now lets read
try {
data=util.readByScanner(TEMPLATESOURCE);
// Now lets check
if(data.length()>0){
data.replaceAll("%title%", subject);
data.replaceAll("%message%", messaging);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Here we return string
return data;
}
/******************* CONSTRUCTING RECEPIENT PARSER METHOD *******************/
private InternetAddress[] mailAddress(String[] mails){
// HERE WE START PROCESSING THE MAIL ADDRESSES
InternetAddress[] address={};
// NOW LETS START
if(mails!=null){
if(mails.length>0){
address=new InternetAddress [mails.length];
for(int i=0; i<mails.length; i++){
try {
address[i]=new InternetAddress(mails[i]);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// Here we return address
return address;
}
/********************** CONSTRUCTING THE PROPERTY METHOD ********************/
private Properties props(){
// HERE WE START SETTING MESSAGE PROPERTIES
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties properties = System.getProperties();
String host = "localhost";
// HERE WE START SETTING
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.host", Setting.get("host"));
properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
// properties.put("mail.smtp.ssl.trust", "*");
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.socketFactory.port", Setting.get("port"));
properties.setProperty("mail.smtp.port", Setting.get("port"));
properties.setProperty("mail.smtp.socketFactory.port", Setting.get("port"));
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.debug", "true");
properties.put("mail.store.protocol", Setting.get("sp"));
properties.put("mail.transport.protocol", Setting.get("tp"));
// Here we return property
return properties;
}
/********************** CONSTRUCTING THE SESSION METHOD ***********************/
private Session session(Properties props){
// HERE WE START SETTING THE SESSION
// Get the default Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Setting.get("username"), Setting.get("password"));
}
});
// Here we return session
return session;
}
/******************** HERE WE CONSTRUCT TRANSPORT CLASS ***********************/
public static final class Transporter implements Callable<Integer>{
// HERE WE CONSTRUCT CLASS
private String Message;
private String Title;
private String[] Mails;
MailTransporter Transport;
public Transporter(MailTransporter transport){
Mails=transport.Mails;
Title=transport.Title;
Message=transport.Messaging;
Transport=transport;
}
/*********** HERE WE CALL THE CALLABLE ***********/
#Override
public Integer call() throws Exception {
return Transport.transport(Mails, Title, Message);
}
// END OF INNER CLASS
}
// END OF OUTER CLASS
}
I can't figure out what is wrong with my code. I can't seem to get the output I desire. The code is not sending my mails and when I try to put it together it's still not working.
I suggest catch any Exception or Error otherwise it will be stored silently in the Future returned by submit which you are discarding.
#Override
public Integer call() throws Exception {
try {
return Transport.transport(Mails, Title, Message);
} catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException(t);
}
}
Without this your tasks will silently die on an Exception or Error and you won't know why

java.util.NoSuchElementException: No line found error java

Keep getting this error
"java.util.NoSuchElementException: No line found error java"
and searched through code so many times and cant see to find problems heres my files can anyone help?
Am currently doing this as an assignment and am trying to transfer it from unthreaded to threaded and in the process came up with this error!!
This is the Client class
package Client;
import core.Email;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.Scanner;
public class EmailClient {
public static void main(String[] args) {
try
{
// Step 1 (on consumer side) - Establish channel of communication
Socket dataSocket = new Socket("localhost", EmailServiceDetails.LISTENING_PORT);
// Step 3) Build output and input objects
OutputStream out = dataSocket.getOutputStream();
PrintWriter output = new PrintWriter(new OutputStreamWriter(out));
InputStream in = dataSocket.getInputStream();
Scanner input = new Scanner(new InputStreamReader(in));
Scanner keyboard = new Scanner(System.in);
String message = "";
while(!message.equals(EmailServiceDetails.END_SESSION))
{
displayMenu();
int choice = getNumber(keyboard);
String response = "";
if(choice >=0 && choice < 3)
{
switch (choice)
{
case 0:
message = EmailServiceDetails.END_SESSION;
// Send message
output.println(message);
output.flush();
response = input.nextLine();
if(response.equals(EmailServiceDetails.SESSION_TERMINATED))
{
System.out.println("Session ended.");
}
break;
case 1:
message = sendEmail(keyboard);
// Send message
output.println(message);
output.flush();
// Get response
response = input.nextLine();
if(response.equals(EmailServiceDetails.SUCCESSFUL_ADD))
{
System.out.println("Email sent successfully");
}
else if(response.equals(EmailServiceDetails.UNSUCCESSFUL_ADD))
{
System.out.println("Sorry, the email could not be sent at this time.");
}
break;
case 2:
message = viewUnread(keyboard);
// Send message
output.println(message);
output.flush();
// Get response
response = input.nextLine();
if(response.equals(EmailServiceDetails.NO_UNREAD))
{
System.out.println("No unread mails found for that account.");
}
else
{
ArrayList<Email> unreadMails = EmailServiceDetails.parseEmailList(response);
System.out.println("Unread Emails:");
for(Email e: unreadMails)
{
System.out.println(e);
}
}
break;
}
if(response.equals(EmailServiceDetails.UNRECOGNISED))
{
System.out.println("Sorry, that request cannot be recognised.");
}
}
else
{
System.out.println("Please select an option from the menu");
}
}
System.out.println("Thank you for using the Email system.");
dataSocket.close();
}catch(Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
}
}
public static void displayMenu()
{
System.out.println("0) Exit");
System.out.println("1) Send an email");
System.out.println("2) View all unread mails");
}
public static int getNumber(Scanner keyboard)
{
boolean numberEntered = false;
int number = 0;
while(!numberEntered)
{
try{
number = keyboard.nextInt();
numberEntered = true;
}
catch(InputMismatchException e)
{
System.out.println("Please enter a number.");
keyboard.nextLine();
}
}
keyboard.nextLine();
return number;
}
public static String sendEmail(Scanner keyboard)
{
System.out.println("Please enter the sender of this email:");
String sender = keyboard.nextLine();
// Get recipient information
String anotherRecipient = "Y";
ArrayList<String> recipients = new ArrayList();
while(anotherRecipient.equalsIgnoreCase("Y"))
{
System.out.println("Enter the recipient's email address:");
String recipient = keyboard.nextLine();
recipients.add(recipient);
System.out.println("Would you like to add another recipient? ('Y' for yes and 'N' for no)");
anotherRecipient = keyboard.nextLine();
}
System.out.println("Please enter the email subject:");
String subject = keyboard.nextLine();
System.out.println("Please enter the message body:");
String body = keyboard.nextLine();
// Get attachment information
ArrayList<String> attachments = new ArrayList();
System.out.println("Would you like to enter an attachment ('Y' to add and 'N' to continue)");
String anotherAttachment = keyboard.nextLine();
while(anotherAttachment.equalsIgnoreCase("Y"))
{
System.out.println("Enter the attachment information:");
String attachment = keyboard.nextLine();
attachments.add(attachment);
System.out.println("Would you like to add another attachment? ('Y' for yes and 'N' to Continue)");
anotherAttachment = keyboard.nextLine();
}
long timestamp = new Date().getTime();
String response = null;
Email e = null;
if(attachments.size() > 0)
{
e = new Email(sender, recipients, subject, body, timestamp, attachments);
}
else
{
e = new Email(sender, recipients, subject, body, timestamp);
}
response = EmailServiceDetails.ADD_MAIL + EmailServiceDetails.COMMAND_SEPARATOR + EmailServiceDetails.formatEmail(e);
return response;
}
public static String viewUnread(Scanner keyboard)
{
System.out.println("Please enter the name of the email account you wish to see unread mail for:");
String recipient = keyboard.nextLine();
String response = EmailServiceDetails.VIEW_UNREAD + EmailServiceDetails.COMMAND_SEPARATOR + recipient;
return response;
}
}
--------------------------------------------------------------------------------
This is Server
---------------
package Server;
import Server.Commands.Command;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class EmailServer {
public static void main(String[] args) {
try{
// Set up a connection socket for other programs to connect to
ServerSocket listeningSocket = new ServerSocket(EmailServiceDetails.LISTENING_PORT);
// Create the list of emails to be stored and worked with
EmailStore emails = new EmailStore();
boolean continueRunning = true;
int threadCount = 0;
while(continueRunning)
{
// Step 2) wait for incoming connection and build communications link
Socket dataSocket = listeningSocket.accept();
threadCount++;
System.out.println("The server has now accepted " + threadCount + " clients");
// Step 3) Build thread
// Thread should be given:
// 1) a group to be stored in
// 2) a name to be listed under
// 3) a socket to communicate through
// 4) Any extra information that should be shared
EmailThread newClient = new EmailThread (emails, dataSocket.getInetAddress()+"", dataSocket,threadCount);
newClient.start();
}
listeningSocket.close();
}
catch(Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
}
}
}
--------------------------------------------------------------------------------
This is ServerThread
---------------
package Server;
import Server.Commands.Command;
import Server.EmailStore;
import core.EmailServiceDetails;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;
/**
*
* #author User
*/
public class EmailThread extends Thread {
private Socket dataSocket;
private Scanner input;
private PrintWriter output;
private int number;
private EmailStore emails;
public EmailThread(EmailStore emails,String name, Socket dataSocket, int number) {
try {
// Save the data socket used for communication between the thread and the Client
this.dataSocket = dataSocket;
// Save the id of the thread to identify output
// Save the id of the thread to identify output
this.number = number;
input = new Scanner(new InputStreamReader(this.dataSocket.getInputStream()));
// Create the stream for writing to the Client
output = new PrintWriter(this.dataSocket.getOutputStream(), true);
} catch (IOException e) {
System.out.println("An exception occurred while setting up connection links for a thread: " + e.getMessage());
}
}
#Override
public void run() {
{
String incomingMessage = "";
String response;
try {
while (!incomingMessage.equals(EmailServiceDetails.END_SESSION)) {
// Wipe the response to make sure we never use an old value
response = null;
// take in information from the client
incomingMessage = input.nextLine();
System.out.println("Received message: " + incomingMessage);
// Break up information into components
String[] components = incomingMessage.split(EmailServiceDetails.COMMAND_SEPARATOR);
// Confirm that the command was correctly formatted
// Did it include more than just the command text?
if (components.length > 1) {
CommandFactory factory = new CommandFactory();
// Figure out which command was sent by the client
// I.e. what does the client want to do?
Command command = factory.createCommand(components[0]);
// Take the remaining text the client sent (i.e. all the information provided)
// and execute the requested action (e.g. store the new mail, get all sent mails etc)
response = command.createResponse(components[1], emails);
} else if (components[0].equals(EmailServiceDetails.END_SESSION)) {
response = EmailServiceDetails.SESSION_TERMINATED;
} else {
// If information was missing, set the response to inform the
// client that the command wasn't recognised
response = EmailServiceDetails.UNRECOGNISED;
}
// Send back the computed response
output.println(response);
output.flush();
}
} catch (Exception e) {
System.out.println("An exception occurred while communicating with client #" + number + ": " + e.getMessage());
} finally {
try {
// Shut down connection
System.out.println("\n* Closing connection with client #" + number + "... *");
dataSocket.close();
} catch (IOException e) {
System.out.println("Unable to disconnect: " + e.getMessage());
System.exit(1);
}
}
}
}
}
--------------------------------------------------------------------------------
This is EmailStore
---------------
package Server;
import core.Email;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class EmailStore
{
private ArrayList<Email> emailList = new ArrayList();
public boolean addMail(Email newEmail)
{
return emailList.add(newEmail);
}
public boolean removeMail(Email mailToBeDeleted)
{
return emailList.remove(mailToBeDeleted);
}
public ArrayList<Email> findEmailByRecipient(String recipient)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails whose recipients list contents the specified recipient
.filter(email -> email.getRecipients().contains(recipient))
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
public ArrayList<Email> findEmailBySender(String sender)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails matching the specified sender
.filter(email -> email.getSender().equals(sender))
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
// Methods to mark emails as read
// Provide a version that marks multiple mails as read AND a version that
// marks a single email as read
public void markMultipleAsRead(ArrayList<Email> emails)
{
for(Email e : emails)
{
markAsRead(e);
}
}
public void markAsRead(Email e)
{
int index = emailList.indexOf(e);
if(index != -1)
{
Email storedMail = emailList.get(index);
storedMail.markAsRead(true);
}
}
// Methods to mark emails as spam
// Provide a version that marks multiple mails as spam AND a version that
// marks a single email as spam
public void markAsSpam(Email e)
{
int index = emailList.indexOf(e);
if(index != -1)
{
Email storedMail = emailList.get(index);
storedMail.markAsSpam(true);
}
}
public void markMultipleAsSpam(ArrayList<Email> emails)
{
for(Email e : emails)
{
markAsSpam(e);
}
}
public ArrayList<Email> findUnreadEmailByRecipient(String recipient)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails whose recipients list contents the specified recipient AND the email is not unread
.filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
}
-------
Help Appreciated
-
----------
Help would be great appreciated as the frustration levels are at a high!!
This answer is a wild guess but in case 1 of the switch statement of the main method you are calling the input.nextLine() scanner which it might not contain information at that time. It is possible that you have to check if data arrived by using the hasNext() method first.
Also in the last method when you are collecting the email classes you don't really need to cast. It can be done like this:
results = emailList.stream()
.filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
.collect(Collectors.toCollection(ArrayList::new));

How can we open a mail with specific subject and specific date in gmail using Java?

I am trying to open a mail in Gmail with a specific subject on a specific date.
I have write down the code where it is fetching all the mails from Gmail in Inbox folder.
How can we get a specific mail content into string format. instead of searching all mails.
how can we search on mails subject name for todays date ?
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 EmailRead {
private static final String MAIL_POP_HOST = "pop.gmail.com";
private static final String MAIL_STORE_TYPE = "pop3";
private static final String POP_USER = "users email";
private static final String POP_PASSWORD = "users password";
private static final String POP_PORT = "995";
public static void getMails(String user, String password) {
user = "slautomation2018#gmail.com";
password = "dontKnow";
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", MAIL_POP_HOST);
properties.put("mail.pop3.port", POP_PORT);
properties.put("mail.pop3.starttls.enable", "true");
properties.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// Session emailSession = Session.getDefaultInstance(properties);
Session emailSession = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(POP_USER, POP_PASSWORD);
}
});
// create the POP3 store object and connect with the pop server
Store store = emailSession.getStore(MAIL_STORE_TYPE);
store.connect(MAIL_POP_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();
int m = messages.length-1;
int y = messages.length-2;
System.out.println(messages[m]);
System.out.println(messages[y]);
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(message.getSubject());
System.out.println(message.getFrom()[0]);
System.out.println(message.getContent().toString());
System.out.println(message.getReceivedDate());
}
// 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) {
getMails(POP_USER, POP_PASSWORD);
}
}

How to extract a "registration" URL from a mail content

I am successful in reading the content of the gmail-email using "JAVAMail" and I am able to store it in a string. Now I want to get a specific registration URL from the content (String). How can I do this, The String contains plenty of tags and href but I want to extract only the URL that is provided in a hyper link on a word " click here" that exist in the below mentioned statement
"Please <a class="h5" href="https://newstaging.mobilous.com/en/user-register/******" target="_blank">click here</a> to complete your registration".
on the hyper link "click here" the url
href="https://newstaging.mobilous.com/en/user-register/******" target="_blank"
I have tried this by using the following code
package email;
import java.util.ArrayList;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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 emailAccess {
public static void check(String host, String storeType, String user,
String password)
{
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.imap.host",host);
properties.put("mail.imap.port", "993");
properties.put("mail.imap.starttls.enable", "true");
properties.setProperty("mail.imap.socketFactory.class","javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.imap.socketFactory.fallback", "false");
properties.setProperty("mail.imap.socketFactory.port",String.valueOf(993));
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("imap");
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);
int n=messages.length;
for (int i = 0; i<n; i++) {
Message message = messages[i];
ArrayList<String> links = new ArrayList<String>();
if(message.getSubject().contains("Thank you for signing up for AppExe")){
String desc=message.getContent().toString();
// System.out.println(desc);
Pattern linkPattern = Pattern.compile(" <a\\b[^>]*href=\"[^>]*>(.*?)</a>", Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
Matcher pageMatcher = linkPattern.matcher(desc);
while(pageMatcher.find()){
links.add(pageMatcher.group());
}
}else{
System.out.println("Email:"+ i + " is not a wanted email");
}
for(String temp:links){
if(temp.contains("user-register")){
System.out.println(temp);
}
}
/*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) {
// TODO Auto-generated method stub
String host = "imap.gmail.com";
String mailStoreType = "imap";
String username = "rameshakur#gmail.com";
String password = "*****";
check(host, mailStoreType, username, password);
}
}
On executing I got the out put as
< class="h5" href="https://newstaging.mobilous.com/en/user-register/******" target="_blank">
How can I extract only the href value i.e. https://newstaging.mobilous.com/en/user-register/******
Please suggest, thanks.
You're close. You're using group(), but you've got a couple issues. Here's some code that should work, replacing just a bit of what you've got:
Pattern linkPattern = Pattern.compile(" <a\\b[^>]*href=\"([^\"]*)[^>]*>(.*?)</a>", Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
Matcher pageMatcher = linkPattern.matcher(desc);
while(pageMatcher.find()){
links.add(pageMatcher.group(1));
}
All I did was to change your pattern so it explicitly looks for the end-quote of the href attribute, then wrapped the portion of the pattern that was the string you're looking for in parentheses.
I also added an argument to the pageMather.group() method, as it needs one.
Tell you the truth, you could probably just use this pattern instead (along with the .group(1) change):
Pattern linkPattern = Pattern.compile("href=\"([^\"]*)", Pattern.CASE_INSENSITIVE|Pattern.DOTALL);

How do I manipulate arrays created from a match.find?

Here is the code I have:
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.*;
public class EmailReader {
public static void main(String args[]) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect ("imap.gmail.com", "email#gmail.com", "password");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for (Message message : messages) {
String subject = message.getSubject();
String location = "AAR|RRC|PSD|TPC|HP|SCC|MCA";
List<String> list = new ArrayList<String>();
System.out.println("SUBJECT: " + subject);
System.out.println("DATE: " + message.getSentDate());
Pattern pattern = Pattern.compile(location);
Matcher match = pattern.matcher(subject);
while (match.find()) {
list.add(match.group());
System.out.println(list);
}
}
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
}
I want the program to read each email while searching for the strings saved in locations and store these in an array. This works fine, however I would like each of the abbreviations in the location string be set to an value for determining mileage. I have no idea how I would go about this. In the end I want to be able to sum up all the values from a certain date range of emails based on the numbers found. So, for example, if AAR was set to 15 and showed up in 3 email subject lines and RRC was set to 8 and showed up in 2, it would sum it all up and print it out.
Ended up using:
if(match.group().contains("AAR"){
Then do this string of code
}
It looks pretty sloppy since I have a bunch of if statements but works. Might be better to use a switch instead.

Categories