Java multithread app not running methods - java

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

Related

Any solution regarding sending a file to IBM MQ

Good afternoon all, I have an issue with IBM MQ, I'm supposed to use JMS to connect to a defined queue then send an XML file to the defined queue. Any help with this problem is gladly appreciated.
In this image it shows that no message is received even though in eclipse IDE it states other wise:
I have a coded application that should work it sends and receives a message the problem is that when I check my IBM MQ explorer and my linux MQ server nothing appears so I'm not sure if its the server configurations that are wrong.
Here is the code I was referring to :
package mqtest;
import javax.jms.Destination;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class JmsIOPutGet {
// System exit status value (assume unset value to be 1)
private static int status = 1;
// Create variables for the connection to MQ
private static final String HOST = "13.246.126.217"; // Host name or IP address
private static final int PORT = 1416; // Listener port for your queue manager
private static final String CHANNEL = "DEV.APP.SVRCONN"; // Channel name
private static final String QMGR = "qm5"; // Queue manager name
private static final String APP_USER = "mqm"; // Windows user name that application uses to connect to MQ
private static final String APP_PASSWORD = "Kion2018"; // Windows user password associated with APP_USER
private static final String QUEUE_NAME = "Q2"; // Queue that the application uses to put and get messages to and from
/**
* Main method
*
* #param args
*/
public static void main(String[] args) {
// Variables
JMSContext context = null;
Destination destination = null;
JMSProducer producer = null;
JMSConsumer consumer = null;
try {
// Create a connection factory
JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactory cf = ff.createConnectionFactory();
// Set the properties
cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
cf.setStringProperty(WMQConstants.USERID, APP_USER);
cf.setStringProperty(WMQConstants.PASSWORD, APP_PASSWORD);
//cf.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SUITE, "*TLS12");
// Create JMS objects
context = cf.createContext();
destination = context.createQueue("queue:///" + QUEUE_NAME);
// Read given file
File myObj = new File("C:\\Users\\Lesego\\OneDrive\\Documents\\Test Files\\application.xml");
Scanner myReader = new Scanner(myObj);
String msg = "";
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
msg = msg + data;
}
myReader.close();
TextMessage message = context.createTextMessage(msg);
producer = context.createProducer();
producer.send(destination, message);
System.out.println("Sent message:\n" + message);
consumer = context.createConsumer(destination); // autoclosable
String receivedMessage = consumer.receiveBody(String.class, 15000); // in ms or 15 seconds
System.out.println("\nReceived message:\n" + receivedMessage);
recordSuccess();
} catch (JMSException jmsex) {
recordFailure(jmsex);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
System.exit(status);
} // end main()
/**
* Record this run as successful.
*/
private static void recordSuccess() {
System.out.println("SUCCESS");
status = 0;
return;
}
/**
* Record this run as failure.
*
* #param ex
*/
private static void recordFailure(Exception ex) {
if (ex != null) {
if (ex instanceof JMSException) {
processJMSException((JMSException) ex);
} else {
System.out.println(ex);
}
}
System.out.println("FAILURE");
status = -1;
return;
}
/**
* Process a JMSException and any associated inner exceptions.
*
* #param jmsex
*/
private static void processJMSException(JMSException jmsex) {
System.out.println(jmsex);
Throwable innerException = jmsex.getLinkedException();
if (innerException != null) {
System.out.println("Inner exception(s):");
}
while (innerException != null) {
System.out.println(innerException);
innerException = innerException.getCause();
}
return;
}

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 send email from using outlook using a java api

I am using the below code to send email from outlook using java. But getting the error.
CODE:
public static void mail (){
// TODO Auto-generated method stub
//String host="POKCPEX07.corp.absc.local";
String host="POKCPEX07.corp.absc.local";
final String user="satpal.gupta#accenture.com";
String to="satpal.gupta#accenture.com";
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.port", "587");
Session session=Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("SGupta#amerisourcebergen.com","******");
}
});
session.setDebug(true);
try {
MimeMessage message = new MimeMessage(session);
message.saveChanges();
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Test mail");
message.setText("This is test mail.");
//send the message
Transport.send(message);
System.out.println("message sent successfully...");
}
catch (MessagingException e) {e.printStackTrace();}
}
}
ERROR:
javax.mail.MessagingException: Could not connect to SMTP host: POKCPEX07.corp.absc.local, port: 587;
nested exception is:
java.net.SocketException: Permission denied: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1227)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:322)
at javax.mail.Service.connect(Service.java:258)
at javax.mail.Service.connect(Service.java:137)
at javax.mail.Service.connect(Service.java:86)
at javax.mail.Transport.send0(Transport.java:150)
at javax.mail.Transport.send(Transport.java:80)
at TestEmail.mail(TestEmail.java:50)
at TestEmail.main(TestEmail.java:16)
package com.sendmail;
import java.util.Date;
import java.util.Properties;
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.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendAttachmentInEmail {
private static final String SERVIDOR_SMTP = "smtp.office365.com";
private static final int PORTA_SERVIDOR_SMTP = 587;
private static final String CONTA_PADRAO = "xxxx#xxx.com"; //Cofig Mail Id
private static final String SENHA_CONTA_PADRAO = "XYZ"; // Password
private final String from = "xxxx#xxx.com";
private final String to = "xxxx#xxx.com";
private final String subject = "Teste";
private final String messageContent = "Teste de Mensagem";
public void sendEmail() {
final Session session = Session.getInstance(this.getEmailProperties(), new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(CONTA_PADRAO, SENHA_CONTA_PADRAO);
}
});
try {
final Message message = new MimeMessage(session);
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setFrom(new InternetAddress(from));
message.setSubject(subject);
message.setText(messageContent);
message.setSentDate(new Date());
Transport.send(message);
} catch (final MessagingException ex) {
System.out.println(" "+ex);
}
}
public Properties getEmailProperties() {
final Properties config = new Properties();
config.put("mail.smtp.auth", "true");
config.put("mail.smtp.starttls.enable", "true");
config.put("mail.smtp.host", SERVIDOR_SMTP);
config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
return config;
}
public static void main(final String[] args) {
new SendAttachmentInEmail().sendEmail();
}
}
As posted by you in comments above, it looks like your SMTP is not configured and by looking your exception - you are using gmail.
Follow this link to configure your SMTP.

Send email to arraylist retrieved from database

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
}
}

Trouble when i'm trying to send an email throught my aplication

I'm having some trouble with my aplication to send an email.
Main code
public static void main(String[] args) throws EmailException, IOException {
ConfiguracaoEmail emailConfig = new ConfiguracaoEmail(new Filial("matriz", true));
emailConfig.setServidor("smtp.gmail.com");
emailConfig.setRemetente("emailFrom#gmail.com");
emailConfig.setTitulo("Teste");
emailConfig.setCodificacao("utf-8");
emailConfig.setAutenticacao("emailFrom#gmail.com");
emailConfig.setSenha("senhaEmail");
emailConfig.setPortaSMTP(465);
emailConfig.setTLS(true);
List<String> emails = new ArrayList<String>();
emails.add("emailTo#gmail.com");
try {
SendMail mail = new SendMail("Teste", " - envio email", emails, emailConfig);
mail.start();
} catch (EmailException e) {
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
}
}
The class ConfiguracaoEmail is just to auxiliate to pass the information.
Class SendEmail
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
public class SendMail extends Thread {
private HtmlEmail email;
public SendMail(String subject, String message, List<String> mailTo, ConfiguracaoEmail config) throws EmailException, IOException {
this.email = emailConfig(config);
email.setSubject(subject);
addTo(mailTo);
}
private void addTo(List<String> mailTo) throws EmailException {
for (String mail : mailTo) {
email.addTo(mail);
}
}
public HtmlEmail getEmail() {
return email;
}
public void setEmail(HtmlEmail email) {
this.email = email;
}
private HtmlEmail emailConfig(ConfiguracaoEmail cfg) throws EmailException {
HtmlEmail email = new HtmlEmail();
email.setDebug(cfg.getDebug());
email.setTLS(cfg.getTLS());
email.setSSL(true);
email.setHostName(cfg.getServidor());
email.setFrom(cfg.getRemetente(), cfg.getTitulo());
email.setCharset(cfg.getCodificacao());
email.setAuthentication(cfg.getAutenticacao(), cfg.getSenha());
email.setSmtpPort(cfg.getPortaSMTP());
email.setSSL(false);
return email;
}
#Override
public void run() {
try {
email.send();
} catch (EmailException e) {
throw new RuntimeException(e);
}
}
}
Someone have any idea what could possible be happening? It doesn't show any error. The email just isn't sent. (Obs: The code is not just it. I just pick the part revelant to the email)
The following code may solve your problem, its worked for me
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "xxxxx"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "xxxxx"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");//587
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
if its not working ,check your jar files
The issue was in the emailConfig method and specifically the following line:
email.setSSL(false);
Removing this line solved the problem in my case.

Categories